The onload event handler
We briefly saw this event handler in the previous chapter. The onload
event gets fired after a certain element is loaded. This can be useful for a number of reasons. For example, if you want to select an element using getElementById
, you'll have to be sure this element is loaded in the DOM already. This event is most commonly used on the window
object, but it can be used on any element. When you use it on window
, this event gets started when the window object is done loading. Here is how to use it:
window.onload = function() {
// whatever needs to happen after the page loads goes here
}
onload
is similar, but it's different for the window and document
objects. The difference depends on the web browser you are using. The load
event fires at the end of the document loading process. Therefore, you will find that all the objects in the document are in the DOM and the assets have finished loading.
You can also use the addEventListener...