Sometimes when you call third party libraries to your website or webpage you may get an error in console like “…. is not defined”. For example if I try to add owl carousel to the website, I should add the script tag and use the function owlCarousel({ params }) in the code, and when I try to load the website the carousel doesn’t work and we will get the following error: owlcarousel is not defined
Cause
The cause of the issue is the third party script was not loaded while we call the function which turns to the error mentioned above
Solution
We should create a fnction that appends the script to <head> and wait for the confirmation to call the function
function loadScript(url, callback) {
var script = document.createElement("script")
script.type = "text/javascript";
if (script.readyState) { // only required for IE <9
script.onreadystatechange = function() {
if (script.readyState === "loaded" || script.readyState === "complete") {
script.onreadystatechange = null;
callback();
}
};
} else { //Others
script.onload = function() {
callback();
};
}
script.src = url;
document.getElementsByTagName("head")[0].appendChild(script);
}
How to call the function?
loadScript("https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/owl.carousel.min.js", function() {
var owl = $("#owl-demo");
owl.owlCarousel({
items: 8,
autoplayTimeout: 3000,
autoplayHoverPause: true,
nav: true,
}
});
});