I try to write a JavaScript function that loads a js script (src
) and performs some callback when the script is loaded.
I also look if a script with the same src
already exists.
My problem is that if the script already loaded, the callback will not be performed. That is NOK.
How to know if the script was already loaded?
importScript: (function (head) {
function loadError(error) {
throw new URIError("The script " +
error.target.src + " is not accessible.");}
return function (url, callback) {
var existingScript = document.querySelectorAll("script[src='" +
url + "']");
var isNewScript = (existingScript.length == 0);
var script;
if (isNewScript) {
script = document.createElement("script")
script.type = "text/javascript";
}
else {
script = existingScript[0];
}
script.onerror = loadError;
if (script.readyState) { //IE
script.onreadystatechange = function () {
if (script.readyState == "loaded" ||
script.readyState == "complete") {
script.onreadystatechange = null;
if (callback) {
callback(); }
}
};
} else { // others than IE
script.onload = callback; }
if (isNewScript) {
script.src = url;
head.appendChild(script); }
}
})(document.head || document.getElementsByTagName("head")[0])
As I understand, the script.readyState == "loaded" || script.readyState == "complete"
could work only for IE, not for other browsers as well...
Usage:
importScript("myScript1.js");
importScript("myScript2.js", /* onload function: */
function () { alert("The script has been OK loaded."); });
I recommend jQuery, it's so easy with that. Life is too short for coding things like that yourself (you will waste hours for supporting all browsers).
$.ajax({
url: "/script.js",
dataType: "script",
success: function() {
console.log("script loaded");
}
});
EDIT:
It's even easier (example from jQuery docs):
$.getScript( "ajax/test.js", function( data, textStatus, jqxhr ) {
console.log(data); // Data returned
console.log(textStatus); // Success
console.log(jqxhr.status); // 200
});
You can also chain done and fail to have additional callbacks:
$.getScript("ajax/test.js")
.done(function(script, textStatus) {
console.log(textStatus);
})
.fail(function(jqxhr, settings, exception) {
console.log("loading script failed.");
});
<script src="path/to/jquery"></script>
<script>
function wait(method) {
if (window.$) {
method();
} else {
setTimeout(function () { wait(method); }, 100); // check every 100ms
}
}
// wait for jQuery
wait(function() {
// jQuery has loaded!
$("#foo").doSomething();
// you can now load other scripts with jQuery:
$.getScript("ajax/test.js")
.done(function(script, textStatus) {
console.log(textStatus);
})
.fail(function(jqxhr, settings, exception) {
console.log("loading script failed.");
});
}
</script>
Well the safest way to check if script is loaded is you can add a simple callback at end of script . Which if exist can be called with some data also to be passed.
if(window.loaded){
window.loaded(params);
}
Once the script loads it will execute this method which you can declare in your parent script which will be called.
Also you can trigger an event on body and listen on that event in other parent code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With