Execute my jQuery script after dynamically inserted jQuery library has finished loading

我与影子孤独终老i 提交于 2020-01-01 00:45:56

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/8864381/execute-my-jquery-script-after-dynamically-inserted-jquery-library-has-finished

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