Skip to content Skip to sidebar Skip to footer

How To Run A Javascript Function After A Specific Js Has Loaded?

I have made a js function for including another Javascript in my html. I need to make sure that the script I have loaded using the function is has completed processing and then onl

Solution 1:

functionloadBackupScript(callback) {
    var script;
    if (typeof callback !== 'function') {
       thrownewError('Not a valid callback');  
    }
    script = document.createElement('script');
    script.onload = callback;  
    script.src = 'http://www.geoplugin.net/javascript.gp';
    document.head.appendChild(script);
}

loadBackupScript(function() { alert('loaded'); });

Solution 2:

Add this to your function:

// all cool browsers
script.onload = doSomething;
// IE 6 & 7
script.onreadystatechange = function() {
if (this.readyState == 'complete') {
    doSomething();
}

IF you don't trust these events you could also use setTimeout() to check for the existence of the function. A good article on this can be found here:

http://www.ejeliot.com/blog/109

Solution 3:

I would recommend using LABJs for this.

Using it you can do this

$LAB
.script("framework.js")
.wait(function(){
    //called when framework.js is loaded
})
.script("init.js")
.wait(function(){
    //called when init.js is loaded
});

This is cross-browser and will often be more efficient than hardcoding script tags into your html due to the way it supports parallel downloads.

You can read more about this here

Post a Comment for "How To Run A Javascript Function After A Specific Js Has Loaded?"