views:

55

answers:

3

Hi, today I've been working on loading dynamic javascript code (files). The solution I use is :

function loadScript(scriptUrl) {
        var head = document.getElementsByTagName("head")[0];
        var script = document.createElement('script');
        script.id = 'uploadScript';
        script.type = 'text/javascript';
        script.src = scriptUrl;
        head.appendChild(script);
    }

the problem with this is that I don't know how to make sure WHEN the script contents are executed. Since the script contains classes (well JS classes), I wrote down a function that is called through setTimeout and checks if those objects are defined. This is not flexible as it is not automatical. So? Are there ways to load those scripts and have a reliable notification on when they have been executed?

+1  A: 

You can use jquery's getScript and pass a callback function.

$.getScript("test.js", function(){
   alert("Script loaded and executed.");
 });

See: jquery.

Topera
eh... unfortunately this has to load jQuery itself uhuhuhu
gotch4
+1. This way you can support dependency and load them in order by nesting the getScript calls in the callback functions.
Fosco
You can check out the jQuery source code, it can be easily implemented using plain JavaScript, see: http://gist.github.com/538106
tszming
+1  A: 

The easiest way short of a JS library is to make an XMLHttpRequest and eval() the return. Your "onload" would be when the data is returned, and "oninit" would be right after you've eval'd.

EDIT: If you want to sequence this, you can create an AssetLoader that takes an array of scripts and won't eval() a script until the one preceding it has been fetched and initialized.

EDIT 2: You can also use the script.onload stuff in the post referenced in the comments. The eval method has a slight advantage in that you can separate and control the load and execution portions of the script import.

EDIT 3: Here's an example. Consider a file called foo.js that contains the following:


function foo () {
    alert('bar');
}

Then execute the following from another page in your browser:



function initScript (scriptString) {
    window.eval(scriptString);
}

function getScript (url, loadCallback, initCallback, callbackScope) {

    var req = new XMLHttpRequest();
    req.open('GET', url);

    req.onreadystatechange = function (e) {

        if (req.readyState == 4) {
            if (loadCallback) loadCallback.apply(callbackScope);
            initScript.call(null, req.responseText);
            if (initCallback) initCallback.apply(callbackScope);
        }

    }

    req.send();

}

function fooScriptLoaded () {
    alert('script loaded');
}

function fooScriptInitialized () {
    alert('script initialized');
    foo();
}

window.onload = function () {
    getScript('foo.js', fooScriptLoaded, fooScriptInitialized, null);
}

You will see the alerts "script loaded", "script initialized", and "bar". Obviously the implementation of XMLHttpRequest here isn't complete and there are all sorts of things you can do for whatever scope you want to execute the script in, but this is the core of it.

sevenflow
Yes, but how do I know that a script has been initialized???
gotch4
After eval() the script has been initialized. You can throw a try-catch block around it to see if any errors prevent the script from initializing.
sevenflow
I put up an edit with example code
sevenflow
tank you very much
gotch4
A: 

You could use a counter variable, and a kind of callback:

var scriptsToLoad = 10;
var loadedScripts = 0;
//...
function increaseLoadCount() {
loadedScripts++;
if(loadedScripts == scriptsToLoad) {
alert("start here");
}
}

//script1-10.js
increaseLoadCount();

Maybe a bit nicer than with a timeout..

Fabian Fritz