How can I execute a JavaScript function after Page Load is completed?
Use the onload
event like this:
window.onload = function(){
// your code here.......
};
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
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With