attachEvent / addEventListener to Window onload / load - preferred way

情到浓时终转凉″ 提交于 2019-12-21 09:15:02

问题


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?


回答1:


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.




回答2:


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

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



来源:https://stackoverflow.com/questions/5436521/attachevent-addeventlistener-to-window-onload-load-preferred-way

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!