简体   繁体   中英

How to call a function after “Complete page load” and “after all external script execution”?

How to call a function after "Complete page load" and "after all external script execution" ?

I tried all 4 below option, but no luck!!!

$(document).ready..
$(window).load...
window.onload = ...
$(document).ready(function()...

Doing setTimeout works for me, But not sure if this 100% efficient!!!!

setTimeout(function(){
//your code here
}, 3000);

Please advice and help!!!

I have been terribly interested with your question and going deep to the jQuery source I came up with a mad hack :)
But the key point is that you should put this piece of code at the very beginning, right after you plug jQuery :

$.statesNum = 0;
$.fn.ready = function ( fn ) {
    $.statesNum++;
    jQuery.ready.promise().done( fn ).then(function () {
        $.statesNum--;
        if ($.statesNum == 0) {
            $(document).trigger("afterReady");
        }
    });

    return this;
};

Now whenever you want to execute something after all .ready functions are done you can do like this:

$(document).on("afterReady", function () {
    alert("Hey, the ready functions are executed");
});

Scripts are loaded and executed in the order they appear in your HTML. If you have simple scripts, just put things you want to run later at the bottom.

However if you have complex scripts that run asynchronously (meaning they run in parallel), then it is impossible to know if they have finished executing without actually looking at what they do. Eg do they (or can they) trigger an event that you can listen to? Or maybe you can use "promise" patterns.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM