user199085 user199085 - 1 year ago 94
Javascript Question

document.createElement('script')... adding two scripts with one callback

I need to add prototype and then add scriptaculous and get a callback when they are both done loading. I am currently loading prototype like so:

var script = document.createElement("script");
script.src = "";
script.onload = script.onreadystatechange = callback;
document.body.appendChild( script );

I could do this by chaining the callbacks, but that seems like poor practice ( I don't want a silly chain of 20 callback methods when I need to load more scripts). Ideas?

Answer Source

I propose you to use some small loader which will chain and do stuff for you. For example like this one:

function loadScripts(array,callback){
    var loader = function(src,handler){
        var script = document.createElement("script");
        script.src = src;
        script.onload = script.onreadystatechange = function(){
            script.onreadystatechange = script.onload = null;
        var head = document.getElementsByTagName("head")[0];
        (head || document.body).appendChild( script );
    (function run(){
            loader(array.shift(), run);
            callback && callback();

This script should help you to build the script tags and call your callback when all files are loaded. Invoke is pretty easy:

    alert('All things are loaded');

Hope this will help

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download