Document Load Events

Now that we’ve covered the fundamentals of JavaScript event handling, we’ll start looking in more detail at specific categories of events. We begin, in this section, with document load events.

Most web applications need notification from the web browser to tell them when the document has been loaded and is ready to be manipulated. The load event on the Window object serves this purpose and was discussed in detail in Chapter 13, which included an onLoad() utility function in Example 13-5. The load event does not fire until a document and all of its images are fully loaded. It is usually safe, however, to start running your scripts after the document is fully parsed but before images are downloaded. You can improve the startup time of your web applications if you trigger your scripts on events other than “load”.

The DOMContentLoaded event is fired when the document has been loaded and parsed and any deferred scripts have been executed. Images and async scripts may still be loading, but the document is ready to be manipulated. (Deferred and async scripts are explained in Synchronous, Asynchronous, and Deferred Scripts.) This event was introduced by Firefox, and it has been adopted by all other browser vendors, including Microsoft in IE9. Despite the “DOM” in its name, it is not part of the DOM Level 3 event standard, but it is standardized by HTML5.

As described in Client-Side JavaScript Timeline, the document.readyState property changes as the document loads. In ...

Get JavaScript: The Definitive Guide, 6th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.