Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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

like image 284
Nithesh Narayanan Avatar asked Jul 16 '10 04:07

Nithesh Narayanan


3 Answers

Use the onload event like this:

window.onload = function(){
  // your code here.......
};
like image 68
Sarfraz Avatar answered Oct 05 '22 07:10

Sarfraz


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

like image 36
David W. Keith Avatar answered Oct 05 '22 07:10

David W. Keith


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.

like image 30
Paul D. Waite Avatar answered Oct 05 '22 06:10

Paul D. Waite