attachEvent / addEventListener to Window onload / load - 首选方式 [英] attachEvent / addEventListener to Window onload / load - preferred way

查看:74
本文介绍了attachEvent / addEventListener to Window onload / load - 首选方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

推荐答案

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

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.

这篇关于attachEvent / addEventListener to Window onload / load - 首选方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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