6

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

1
  • 5
    @Funky Dude: I think newbie questions are fine on Stack Overflow. When people Google it in future, they’ll end up here, and get some great answers. Commented Jul 21, 2010 at 14:55

4 Answers 4

7

Use the onload event like this:

window.onload = function(){
  // your code here.......
};
Sign up to request clarification or add additional context in comments.

2 Comments

W3C has a newer recommended method for doing this that is far more powerful: element.addEventListener()
@Pullets Forever: Ok that is interesting.
7

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

Comments

1

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.