简体   繁体   English

如何判断$(window).load()/ window.onload事件是否已经触发?

[英]How to tell whether the $(window).load()/window.onload event has already fired?

I have a script that is being inserted dynamically via another script. 我有一个脚本,通过另一个脚本动态插入。 The code in that script is wrapped inside the $(window).load() event because it requires the images on the page to have all loaded. 该脚本中的代码包含在$(window).load()事件中,因为它要求页面上的图像全部加载。 In some browsers it works fine, but in others it seems not to fire because the page has already finished loading by the time the code is run. 在某些浏览器中,它可以正常工作,但在其他浏览器中它似乎不会触发,因为在运行代码时页面已经完成加载。

Is there any way to check and see whether the page has already finished loading - either via jQuery or JavaScript? 有没有办法检查并查看页面是否已经完成加载 - 通过jQuery还是JavaScript? (including images) (包括图片)

In this situation, I don't have access to the onload event of the original document (aside from altering it via the loaded script - but that would seem to present the same problem). 在这种情况下,我无法访问原始文档的onload事件(除了通过加载的脚本更改它 - 但这似乎会出现同样的问题)。

Any ideas/solutions/advice would be greatly appreciated! 任何想法/解决方案/建议将不胜感激!

You could try setting up a handler that's invoked via a timeout that will check the images to see if their properties are available. 您可以尝试设置通过超时调用的处理程序,该处理程序将检查图像以查看其属性是否可用。 Clear the timer in the load event handler so if the load event occurs first, the timer won't fire. 清除load事件处理程序中的计时器,这样如果首先发生load事件,计时器将不会触发。 If the properties aren't available, then the load event hasn't fired yet and you know that your handler will eventually be invoked. 如果属性不可用,则load事件尚未触发,并且您知道最终将调用您的处理程序。 If they are, then you know that the load event occurred before your handler was set and you can simply proceed. 如果是,那么您知道在设置处理程序之前发生了加载事件,您可以继续操作。

Pseudocode 伪代码

 var timer = null;
 $(function() {
    $(window).load( function() {
        if (timer) {
           clearTimeout(timer);
           timer = null;
        }
        process();
    });
    timer = setTimeout( function() {
        if (checkAvailable())
           process();
        }
    }, 10*1000 ); // waits 10 seconds before checking
 });

 function checkAvailable()
 {
     var available = true;
     $('img').each( function() {
         try {
             if (this.height == 0) {
                available = false;
                return false;
             }
         }
         catch (e) {
             available = false;
             return false;
         }
      });
      return available;
  }

  function process() {
      ... do the real work here
  }

我写了一个可能有用的插件: http//plugins.jquery.com/project/window-loaded

我认为如果你使用$(document).ready而不是$(window).load,你的问题就会自行解决 - 请参阅jquery文档

Don't know if this is what you are after, but have you tried(?): 不知道这是不是你想要的,但是你试过(?):

$(document).ready(function(){
    ...
});

http://docs.jquery.com/Events/ready#fn http://docs.jquery.com/Events/ready#fn

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

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