tags:

views:

63

answers:

4

How can I execute a JavaScript function after Page Load is completed?

Thanks in advance.

A: 

Use the onload event like this:

window.onload = function(){
  // your code here.......
};
Sarfraz
W3C has a newer recommended method for doing this that is far more powerful: element.addEventListener()
Pullets Forever
@Pullets Forever: Ok that is interesting.
Sarfraz
A: 

Event.observe(window, "onload", yourFunction);

Newbie
+3  A: 

To get your onload handler to work cleanly in all browsers:

if (addEventListener in document) { // use W3C standard method
    document.addEventListener('load', yourFunction, false);
} else { // fall back to traditional method
    document.onload = yourFunction;
}

See http://www.quirksmode.org/js/events_advanced.html for more detail

Pullets Forever
A: 

Most JavaScript frameworks (e.g. jQuery, Prototype) encapsulate similar functionality to this.

For example, in jQuery, passing a function of your own to the core jQuery function $() results in your function being called when the page’s DOM is loaded. See http://api.jquery.com/jQuery/#jQuery3.

This occurs before the onload event fires, as onload waits for all external files like images to be downloaded. Your JavaScript probably only needs the DOM to be ready; if so, this approach is preferable to waiting for onload.

Paul D. Waite