简体   繁体   English

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

[英]Cross-browser compatible way to bind events on page load

Using jQuery , I can use the following function to execute code as soon as the DOM has loaded:使用jQuery ,我可以使用以下 function 在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?有没有更好的方法来实现这个功能?

Yes it is cross-browser compatible, but onLoad waits for everything on the page to load before it fires.是的,它是跨浏览器兼容的,但是onLoad在触发之前会等待页面上的所有内容加载。 Internally jQuery.ready uses the DOMContentLoaded event and a few hacks to support older browsers that don't support DOMContentLoaded .在内部jQuery.ready使用DOMContentLoaded事件和一些技巧来支持不支持DOMContentLoaded的旧浏览器。 Most modern browsers support DOMContentLoaded including IE starting with version 9. You can test whether a browser supports DOMContentLoaded using this page .大多数现代浏览器都支持DOMContentLoaded ,包括从版本 9 开始的 IE。您可以使用此页面测试浏览器是否支持DOMContentLoaded

If you are not using a DOM library such as jQuery which has built in support for DOMContentLoaded , you could use DOMContentLoaded and then fallback to onLoad if the browser doesn't support it.如果您没有使用内置支持DOMContentLoaded的 DOM 库,例如 jQuery ,您可以使用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 DOMContentLoaded without a backup.除非您期望访问者使用 IE8 等非常旧的浏览器,否则您完全可以安全地使用DOMContentLoaded而无需备份。

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

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

The window onload method is cross-browser compatible, but there is a better alternative. window 加载方法是跨浏览器兼容的,但有更好的选择。

  • The jQuery ready event fires when the DOM is ready. jQuery 就绪事件在 DOM 就绪时触发。
  • The window onload event fires when all data is downloaded.下载所有数据后,将触发 window 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. html 文件将在图像下载完成之前很久就完成下载并准备好进行操作。 So jQuery's ready event shoots and you can start doing great JavaScript stuff while all those pretty pics download.所以 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.但是,您一次只能在 onload 事件上设置一个方法。 You can, however, set jQuery's ready event multiple times and each method will get called sequentially.但是,您可以多次设置 jQuery 的就绪事件,并且每个方法都将按顺序调用。

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!希望能帮助到你!

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

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