Aayush Aayush - 11 days ago 5
Javascript Question

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 only move further in my original script.

function loadBackupScript(){
var script = document.createElement('script');
script.src = 'http://www.geoplugin.net/javascript.gp';
script.type = 'text/javascript';
var head = document.getElementsByTagName("head")[0];
head.appendChild(script);
}


I need to know that the script has loaded to use its functions ahead. How do I do that?

Answer
function loadBackupScript(callback) {
    var script;
    if (typeof callback !== 'function') {
       throw new Error('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'); });