when using the module pattern in js i’ve notice that the main benefits are private members and not cluttering the global namespace, but what i wanted to know is, is this:
(function(){
//some code...
})();
the same as this:
window.onload = function(){
//some code...
}
they both provide private members and both don’t clutter the global namespace. the only difference i can see is that if both are manipulating DOM elements the second one can be called anywhere within the document (because of document.onload) while the first has to be called ether at the bottom of the body node or right after the close of the body node.
are there any other differences between the two that i may be missing?
One major difference is that the latter will overwrite any existing
window.onloadthat may have been set earlier on the page — and will, in turn, be overwritten by any later ones. (This can be addressed by usingwindow.addEventListenerinstead.)