Saturday, 15 March 2014

How to detect when a page has finished loading in JavaScript

Problem
You want to run a function after the page is finished loading.
Solution
Capture the load event via the onload event handler on the window:
window.onload=functionName;
Or:
window.onload=function() {
var someDiv = document.getElementById("somediv");
...
}
Prior to accessing any page element, you have to first make sure it’s been loaded into the browser. You could add a script block into the web page after the element. A better approach, though, is to capture the window load event and do your element manipulation at that time.
This recipe uses the DOM Level 0 event handling, which assigns a function or functionality to an event handler. An event handler is an object property with this syntax: element.onevent=functionName;
Where element is the target element for the event, and onevent is the specific event handler. Since the event handler is a property of the window object, as other objects also have access to their own event handler properties, it’s accessed using dot notation (.), which is how object properties are accessed in JavaScript.
The window onload event handler in the solution is assigned as follows:
window.onload=functionName;
You could also use the onload event handler directly in the element. For the window load event, attach the onload event handler to the body element:
<body onload="functionName()">
Use caution with assigning event handlers directly in elements, though, as it becomes more difficult to find them if you need to change them at a later time. There’s also a good likelihood of element event handlers eventually being deprecated.

No comments:

Post a Comment