Jump to content

How to Detect When the Page Has Finished Loading with JavaScript

0
  chco's Photo
Posted Jul 22 2010 06:24 PM

This excerpt from Javascript Cookbook shows you how to run a function after your web page has loaded.
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.

Cover of Javascript Cookbook
Learn more about this topic from Javascript Cookbook. 

Covering both ECMAScript 5 and HTML5, Javascript Cookbook helps you take advantage of the latest web features, including HTML5's persistent storage mechanisms and drawing canvas. You'll find solutions for integrating these features with Javascript into UIs that people will enjoy using. The recipes in this book not only help you get things done, they'll also help you develop applications that work reliably in every browser.

Learn More Read Now on Safari


Tags:
0 Subscribe


0 Replies