Webessence

Dynamically add javascript files

There are some caveats when dynamically adding SCRIPT tags. To know when the added script has been downloaded, you can use the following function. It makes use of the load event when available with a fallback to the readystatechange event. The callback has access to the SCRIPT tag (this) and the event object.

function includeScript(src, callback) {
var script = document.createElement("script");
// IE will download the script as soon as the attribute src is set.
script.setAttribute("src", src);

if (typeof script.onload !== "undefined") {
// Chrome, Firefox and IE9
script.onload = callback;
} else if (typeof script.readyState !== "undefined") {
// IE < 9
script.onreadystatechange = function() {
if (script.readyState == "loaded" || script.readyState == "complete") {
script.onreadystatechange = null;
callback.call(script, window.event);
}
};
}

document.getElementsByTagName("head")[0].appendChild(script);
}

// this = SCRIPT element.
// e = event object.
function scriptLoaded(e) {
alert("I downloaded " + this.src + " and the event was: " + e.type);
}

To add a script and execute some code after the script has been downloaded:

includeScript("test.js", scriptLoaded);

As in the article http://www.blaze.io/technical/ies-premature-execution-problem/ is explained, always add the created SCRIPT element to an element that is already attached to the DOM (like the HEAD element).

Javascript | 2011-12-27 12:30:22 | Comments (0)

Comments

No comments.

Make a comment