如何判断$(window).load()/ window.onload事件是否已经触发? [英] How to tell whether the $(window).load()/window.onload event has already fired?

查看:358
本文介绍了如何判断$(window).load()/ window.onload事件是否已经触发?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个通过另一个脚本动态插入的脚本。该脚本中的代码包含在 $(window).load()事件中,因为它要求页面上的图像全部加载。在某些浏览器中它可以正常工作,但在其他浏览器中它似乎不会触发,因为在代码运行时页面已经完成加载。

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. 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.

有没有办法检查并查看页面是否已经完成加载 - 通过jQuery或JavaScript? (包括图片)

Is there any way to check and see whether the page has already finished loading - either via jQuery or JavaScript? (including images)

在这种情况下,我无法访问原始文档的 onload 事件(除了通过加载的脚本改变它 - 但这似乎会带来同样的问题)。

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).

任何想法/解决方案/建议都将不胜感激!

Any ideas/solutions/advice would be greatly appreciated!

推荐答案

您可以尝试设置一个通过超时调用的处理程序,该处理程序将检查图像以查看其属性是否可用。清除 load 事件处理程序中的计时器,因此如果首先发生加载事件,则不会触发计时器。如果属性不可用,则load事件尚未触发,并且您知道最终将调用您的处理程序。如果是,那么您知道在设置处理程序之前发生了加载事件,您可以继续。

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. If the properties aren't available, then the load event hasn't fired yet and you know that your handler will eventually be invoked. If they are, then you know that the load event occurred before your handler was set and you can simply proceed.

Pseudocode

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
  }

这篇关于如何判断$(window).load()/ window.onload事件是否已经触发?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆