Javascript attachEvent / addEventListener 到 Window onload / load - 首选方式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5436521/
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-08-23 17:11:47  来源:igfitidea点击:

attachEvent / addEventListener to Window onload / load - preferred way

javascriptjavascript-events

提问by bryan sammon

I have a script that starts when the page loads and I had been using this code below to start it:

我有一个在页面加载时启动的脚本,我一直在使用下面的代码来启动它:

if (window.addEventListener) {
  window.addEventListener('load', otherRelatedParts, false);
}
else if (window.attachEvent) {
  window.attachEvent('onload', otherRelatedParts );
}

but today I tried with a self invoking function like this:

但今天我尝试使用这样的自调用函数:

(function() {
otherRelatedParts();
}())

It seems to work, in all browsers and is less code. Is this the preferred way to add events to the window load?

它似乎在所有浏览器中都有效,并且代码更少。这是向窗口加载添加事件的首选方法吗?

回答by Atanas Korchev

Your self invoking function will execute earlier than window.onload. It will execute at the moment the browser reads it. In most cases it actually does not make any difference so you can use it this way. Window.load is normally raised when all objects (images, JavaScript files etc) have been downloaded. $(document).ready() triggers earlier than window.onload - when the DOM is ready for manipulation.

您的自调用函数将早于 window.onload 执行。它将在浏览器读取它的那一刻执行。在大多数情况下,它实际上没有任何区别,因此您可以通过这种方式使用它。Window.load 通常在所有对象(图像、JavaScript 文件等)都已下载后引发。$(document).ready() 在 window.onload 之前触发 - 当 DOM 准备好进行操作时。

回答by mkluwe

I guess the above ifclause is written to cover some cross browser issues. You should factor these things out of your code.

我猜上面的if条款是为了涵盖一些跨浏览器问题。你应该把这些东西从你的代码中分解出来。

As other people have done this before, you might as well use some library as jQuery. You should look for .ready()there.

正如其他人以前做过的那样,您不妨使用一些库作为jQuery。你应该在那里寻找.ready()