attachEvent / addEventListener to Window onload / load - preferred way
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 a开发者_如何学Godd events to the window load?
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.
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.
精彩评论