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

后端 未结 1 1340
忘掉有多难
忘掉有多难 2021-02-06 17:38

I am dynamically inserting the jQuery library on a page via

1条回答
  •  旧时难觅i
    2021-02-06 18:11

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

    0 讨论(0)
提交回复
热议问题