Ash Blue
Ash Blue

Reputation: 5582

Ordered JavaScript File Loading

I need to dynamically load several JavaScript file assets in a very specific order after a page has loaded. I'm trying to use onload, but this seems to fire before the asset has fully loaded. How should I adjust the below script to fire a proper callback to load the next script?

Note: Only needs to work in the latest Chrome, Firefox, Safari, and IE9.

function loadAssets() {
    // Setup script
    var scriptJS = document.createElement('script');
    scriptJS.type = 'text/javascript';
    scriptJS.src = objectUrl;

    scriptJS.onload = loadAssetsNext();

    // Begin insertion
    var headerJS = document.getElementsByTagName('HEAD');
    headerJS[0].appendChild(scriptJS);
},
function loadAssetsNext() {
    // Increment object counter
    objectsCount++;
    
    // Test to see if you should call another item
    if ((objectsCount) < objects.length) {
        // Setup script
        var scriptJS = document.createElement('script');
        scriptJS.type = 'text/javascript';
        scriptJS.src = nextObjectUrl;
        
        // Declare callback to fire after script has fully loaded
        scriptJS.onload = loadAssetsNext();
    
        // Begin insertion
        var headerJS = document.getElementsByTagName('HEAD');
        headerJS[0].appendChild(scriptJS);
    }
}

What I need is something like scriptJS.fullyLoaded = doStuff. Have no clue where to go from here though.

PS: jQuery is not an option or another library. You should be able to do this by slightly modifying the above script.

Upvotes: 2

Views: 126

Answers (2)

Zlatko
Zlatko

Reputation: 19569

I think the problem is that your scriptJS.onload = loadAssetsNext(); is placed before headerJS[0].appendChild(scriptJS); That means that your scripts would load and get appended to the page like this:
load script 1
load script 2
load script 3
...
append script 3
append script 2
append script 1

So I think you should just reorder your script a little bit.

Upvotes: 0

Shad
Shad

Reputation: 15451

The reason your onload event is firing immediately is that you are calling it, not assigning it.

scriptJS.onload = loadAssetsNext();

This just assigns the returned value from the call to loadAssetsNext to the property onload of the scriptJS object. What you are intending to do is:

scriptJS.onload = loadAssetsNext;

That sets the onload handler to be the loadAssests function. This should take care of your issues.

Upvotes: 2

Related Questions