The OnLoad event is triggered when the entire page has loaded. This is moment when the globe or loader in your browser's title bar stops spinning. At this point all scripts and stylesheets have finished loading and have been executed, and all images have been downloaded and displayed.
So how do we hook into each of these events; and more importantly, when should we use each? To examine the different hooks, let's have a look at this simple HTML page and the output that it produces.
external.js Loaded and Executed DOM Loaded (DOMContentLoaded) dom.js Loaded and Executed Page Loaded (OnLoad) ajax.js Loaded and Executed dom_ajax.js Loaded and Executed page_ajax.js Loaded and Executed
Let's take a look at each of these windows and see which one best suits our needs.
These scritpts (dom.js) are executed once the DOM is ready to be manipulated. This where you want to put any code that actually changes the page visually as this is the earliest point at which DOM manipulation is possible, and it will be executed before the page is displayed. This is a good thing because we don't want the page elements jumping around and changing style after they are visible to the user.
These scripts (ajax requests and anything in the window.load callback) are executed after the page has completed loading and the user can view the entire document. This is a great place to load long-running scripts and scripts that don't visually alter the page. Some examples of this include analytics and reporting libraries and code or data that might be used later and can be pre-fetched for the user. Google maps loads all of its map tiles using AJAX so that the page load is not halted.