How can I use javascript to determine if an HTMLScriptElement has already been fully loaded?
How can I determine if a dynamically loaded script has finished loading
Lazy Implementation: Create an array that you can use to push the source of all loaded scripts onto, and as they load, push them onto the list. Each time, check to see if the given src is in the array, and if it is, fire the callback immediately.
What you do with the case when its appended, but not loaded becomes the question. If you want the callback to fire, but you want it to fire after it loads, you could do an associative array with a src as the key, and the script element as the value. From there, make the onload or onreadystatechange fire twice by wrapping the original, like so:
var temponload = element.onreadystatechange || element.onload;
if (element.onreadystatechange === undefined)
element.onload = function(e) { temponload(); temponload(); };
else
element.onreadystatechange = function (e) { temponload(); temponload(); };
You have other code which may need to hook into this, but this should get you started hopefully.
You can't really tell when a script has loaded. You can put a global variable in the script you want to check and then test for its presence.
There is a new project called LABjs (Loading and Blocking Javascript) in order to load scripts dynamically and thus tell when they are actually loaded (http://blog.getify.com/2009/11/labjs-new-hotness-for-script-loading/ <- check it out)
Why not add an id to the script element? Check to see if the id exists before continuing....
function includeJs(jsFilePath) {
if (document.getElementById(jsFilePath+"_script")) {
return;
}
var js = document.createElement("script");
js.type = "text/javascript";
js.id = jsFilePath+"_script";
js.src = jsFilePath;
document.body.appendChild(js);
}