One of the most intriguing problems with JavaScript's events related to loading actions is finding the exact sequence where they actually take place. We're all accustomed to attach a load
event when the page is loading, for example using the global window
object. If you use a JavaScript framework, such as jQuery, this problem is trivial because of the normalization that such frameworks perform on events. For example:
$(window).load(function() { alert('Window loaded'); $(document).ready(function() { alert('Document loaded'); }); });
This works just fine in jQuery. But is this true also for our plain old JavaScript code? No. For example, this naive attempt won't work:
var bodyElem = document.body; window.onload = function() { alert('Window loaded'); bodyElem.onload = function() { alert('Document loaded'); }; };
But an old-fashioned coding style which makes use of inline JavaScript works fine:
<body onload="alert('Document loaded')">
Also, things behave differently if your code is placed in the head
or body
sections, obviously due to HTML parsing and DOM construction. Are you confused? The best thing we can do in such cases is trying to stick to the DOM specifications, for example by using the DOMContentLoaded
event when available or simply placing our methods within an object (such as window
) and then wait until the DOM is fully constructed for executing the rest of our code.
And, of course, body
and document
are not the same thing, though it's not possible to attach a load
event to the latter element directly.