How to run a javascript function after a specific JS has loaded?

梦想的初衷 提交于 2020-01-02 03:52:05

问题


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?


回答1:


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'); });



回答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




回答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



来源:https://stackoverflow.com/questions/4323723/how-to-run-a-javascript-function-after-a-specific-js-has-loaded

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!