动态插入jQuery库完成加载后执行我的jQuery脚本 [英] Execute my jQuery script after dynamically inserted jQuery library has finished loading

查看:141
本文介绍了动态插入jQuery库完成加载后执行我的jQuery脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过< script> 标签动态地在页面上插入jQuery库:

  jq = document.createElement('script'); 
jq.setAttribute('src','// ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js');
b.appendChild(jq);

然后我有一些jQuery脚本,需要在jQuery库加载完成后运行,并准备好使用:

  $(f).load(function(){
$(f).fadein(1000) ;
});

如何使其等待加载jQuery?

解决方案

在要插入的脚本标签中指定 onload 事件:

  function onLoad(){
$(f).load(function(){
$(f).fadein(1000);
});
}

jq = document.createElement('script');
jq.onload = onLoad; //< - 魔术
jq.src ='//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js';
b.appendChild(jq);

另一种方法是,如果无法控制脚本插入代码,可以使用一个轮询器: p>

 (function(){
function onLoad(){...} //要运行的代码

if('jQuery'in window)onLoad();
else {
var t = setInterval(function(){//运行poller
if('jQuery'in window ){
onLoad();
clearInterval(t); //停止轮询
}
},50);
}
})() ;


I am dynamically inserting the jQuery library on a page via <script> tag:

jq = document.createElement('script');
jq.setAttribute('src','//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js');
b.appendChild(jq);

Then I have some jQuery script that needs to run after the jQuery library has finished loading and is ready for use:

$(f).load(function() {
    $(f).fadein(1000);
});

How can I make it wait for jQuery to load?

解决方案

Specify an onload event at the to-be-inserted script tag:

function onLoad() {
    $(f).load(function() {
        $(f).fadein(1000);
    });
}

jq = document.createElement('script');
jq.onload = onLoad;   // <-- The magic
jq.src = '//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js';
b.appendChild(jq);

An alternative way, if you cannot control the script insertion code, you can use a poller:

(function() {
    function onLoad() { ... } // Code to be run

    if ('jQuery' in window) onLoad();
    else {
        var t = setInterval(function() { // Run poller
            if ('jQuery' in window) {
                onLoad();
                clearInterval(t);        // Stop poller
            }
        }, 50);
    }
})();

这篇关于动态插入jQuery库完成加载后执行我的jQuery脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆