最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

dom events - How to run a Javascript function after a specific JS has loaded? - Stack Overflow

programmeradmin7浏览0评论

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

function loadBackupScript(){
    var script = document.createElement('script');
    script.src = '.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?

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

function loadBackupScript(){
    var script = document.createElement('script');
    script.src = 'http://www.geoplugin/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?

Share Improve this question edited Jul 26, 2021 at 17:41 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Dec 1, 2010 at 11:12 AayushAayush 3,09810 gold badges50 silver badges73 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 11
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/javascript.gp';
    document.head.appendChild(script);
}

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

Add this to your function:

// all cool browsers
script.onload = doSomething;
// IE 6 & 7
script.onreadystatechange = function() {
if (this.readyState == 'plete') {
    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./blog/109

I would remend 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

发布评论

评论列表(0)

  1. 暂无评论