Why we should use window.onload ? Without this the would not run correctly | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Why we should use window.onload ? Without this the would not run correctly

js

14th Sep 2018, 7:50 PM
Mohsen Khoshsirat
Mohsen Khoshsirat - avatar
2 Answers
+ 3
To be correct 'onload' waits until your stylesheets, scripts, pictures, & all external resources have loaded and document is ready. It's 'DOMContentLoaded' event which fires when your document is ready without waiting for external resources. #addional info below https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onload https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded https://javascript.info/onload-ondomcontentloaded Edit Ipang No problem ; ) Perhaps try sending a bug report. I hear the response time has increased and you get one usually in 3 days. I hope this does not cause any app crash : D
15th Sep 2018, 3:58 AM
Lord Krishna
Lord Krishna - avatar
+ 2
The onload event of window object is fired when the DOM has been completely built based on the document contents, along with completion of loading phase of necessary resources needed to have a complete view of the page (scripts, stylesheets, images, multimedia etc.) By overriding the event handler with a custom function of our own, we can execute JS code to manipulate the DOM safely, knowing the DOM is perfectly rendered. While without doing it, we risk to trigger error due to the fact that an object we refer to isn't available yet in the DOM. (Edited) Thanks @Lord Krishna for correction, I revise my post : ) P.S. I don't know why I can't tag anyone on edited post, app crashes if I try : ( Hth, cmiiw
15th Sep 2018, 3:38 AM
Ipang