javascript 在页面加载时绑定事件的跨浏览器兼容方式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6352789/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 20:23:05  来源:igfitidea点击:

Cross-browser compatible way to bind events on page load

javascriptjquerycross-browsercompatibility

提问by aligray

Using jQuery, I can use the following function to execute code as soon as the DOMhas loaded:

使用jQuery,我可以使用以下函数在DOM加载后立即执行代码:

$(function() {
    // do stuff here
});

Or equivalently:

或等效地:

$(document).ready(function() { 
    // do stuff here
});

In trying to get a better understanding of raw javascript, I'm using this code to achieve a similar effect:

为了更好地理解原始 javascript,我使用此代码来实现类似的效果:

window.onload = function() {
    // do stuff here
}

Is this method cross-browser compatible? Are there any better ways to achieve this functionality?

这种方法是否跨浏览器兼容?有没有更好的方法来实现这个功能?

回答by Useless Code

Yes it is cross-browser compatible, but onLoadwaits for everythingon the page to load before it fires. Internally jQuery.readyuses the DOMContentLoadedeventand a few hacks to support older browsers that don't support DOMContentLoaded. Most modern browsers support DOMContentLoadedincluding IE starting with version 9. You can test whether a browser supports DOMContentLoadedusing this page.

是的,它是跨浏览器兼容的,但它会在触发之前onLoad等待页面上的所有内容加载完毕。在内部jQuery.ready使用该DOMContentLoaded事件和一些 hack 来支持不支持DOMContentLoaded. 大多数现代浏览器都支持DOMContentLoadedIE,从版本 9 开始。您可以测试浏览器是否支持DOMContentLoaded使用此页面

If you are not using a DOM library such as jQuery which has built in support for DOMContentLoaded, you could use DOMContentLoadedand then fallback to onLoadif the browser doesn't support it.

如果您没有使用内置支持 的 DOM 库(例如 jQuery)DOMContentLoaded,您可以使用DOMContentLoaded然后回退到onLoad浏览器不支持它的情况。

(function () { // Encapsulating our variables with a IIFE
  var hasRun = false;  // a flag to make sure we only fire the event once
                       // in browsers that support both events
  var loadHandler = function (evt) {
    if (!hasRun) {
      hasRun = true;
      console.log('loaded via ' + evt.type);
    }
  };
  
  document.addEventListener('DOMContentLoaded', loadHandler, false);
  window.addEventListener('load', loadHandler, false);
}());

Unless you are expecting visitors with very old browsers like IE8, you are totally safe to just use DOMContentLoadedwithout a backup.

除非您希望访问者使用非常旧的浏览器(如 IE8),DOMContentLoaded否则无需备份就可以完全安全地使用。

document.addEventListener('DOMContentLoaded', function (evt) {
  console.log('loaded via ' + evt.type);
}, false);

回答by Will

This is similar to what JQuery does:

这类似于 JQuery 所做的:

window.$ = {};
$.ready = function(fn) {
  if (document.readyState == "complete")
      return fn();

  if (window.addEventListener)
      window.addEventListener("load", fn, false);
  else if (window.attachEvent)
      window.attachEvent("onload", fn);
  else
      window.onload = fn;
}

And to use it:

并使用它:

$.ready(function() {
  // code here...
});

回答by Abishai Gray

The window onload method is cross-browser compatible, but there is a better alternative.

窗口加载方法是跨浏览器兼容的,但还有更好的选择。

  • The jQuery ready event fires when the DOM is ready.
  • The window onload event fires when all data is downloaded.
  • 当 DOM 准备好时触发 jQuery 准备好事件。
  • 下载所有数据后,将触发窗口 onload 事件。

So, let's say you have lots of images (or one BIG one) on your page. The html file will finish downloading and be ready for manipulation long before the images are done downloading. So jQuery's ready event shoots and you can start doing great JavaScript stuff while all those pretty pics download.

因此,假设您的页面上有很多图片(或一张大图片)。html 文件将在图像下载完成之前完成下载并准备好进行操作。因此,jQuery 的就绪事件开始拍摄,您可以在下载所有漂亮图片的同时开始制作出色的 JavaScript 内容。

That's one of the reasons it's a good idea to use a js library.

这就是使用 js 库是个好主意的原因之一。

When there aren't that many images then the difference is negligible. Though, you can only set ONE method at a time on the onload event. You can, however, set jQuery's ready event multiple times and each method will get called sequentially.

当没有那么多图像时,差异可以忽略不计。但是,您一次只能在 onload 事件上设置一种方法。但是,您可以多次设置 jQuery 的就绪事件,并且每个方法都将按顺序调用。

回答by Vern

Cross-browser compatibility would have to depend on how you define the term "browser". Like for instance if it's a text based browser, then it might not be what you're looking for.

跨浏览器兼容性必须取决于您如何定义术语“浏览器”。例如,如果它是基于文本的浏览器,那么它可能不是您想要的。

To answer your question, it will be cross-browser compatible if that particular browser warrants window.onload feature.

为了回答您的问题,如果该特定浏览器保证 window.onload 功能,它将是跨浏览器兼容的。

As a general guide, we usually use libraries that are tested so that we allow the libraries to take care of such "cross-browser" compatibility and we deal with the actual application logic.

作为一般指南,我们通常使用经过测试的库,以便我们允许库处理这种“跨浏览器”兼容性,并处理实际的应用程序逻辑。

Hope it helps!

希望能帮助到你!