简体   繁体   English

在“完成页面加载”和“所有外部脚本执行之后”如何调用函数?

[英]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!!! 我尝试了以下所有4个选项,但是没有运气!!!

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

Doing setTimeout works for me, But not sure if this 100% efficient!!!! 做setTimeout对我有用,但是不确定是否100%有效!!!!

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 :) 我一直对您的问题非常感兴趣,并深入研究了我发疯的jQuery源码:)
But the key point is that you should put this piece of code at the very beginning, right after you plug jQuery : 但是关键是您应该在插入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: 现在,只要您想在完成所有.ready函数之后执行某些操作,就可以像这样:

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

Scripts are loaded and executed in the order they appear in your HTML. 脚本按照它们在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. 或者,您可以使用“承诺”模式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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