Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript "window.onload" – is "window" really necessary?

I see people use "window.onload" all the time, but why? Isn't the "window" part completely superfluous?

like image 908
jedmao Avatar asked Aug 05 '09 20:08

jedmao


People also ask

Why do we need window onload?

The onload event occurs when an object has been loaded. onload is most often used within the <body> element to execute a script once a web page has completely loaded all content (including images, script files, CSS files, etc.).

What is faster than window onload?

ready function event executes a bit earlier than window. onload and is called once the DOM(Document object model) is loaded on your page. It will not wait for the images, frames to get fully load.

Is onload necessary?

Yes, there could be unexpected consequences. But, no, it's not absolutely necessary. The timing could be off for things still loading, like complicated layouts, deep DOM structures, dynamic HTML from other scripts, or images. To avoid these situations, it's always safest to wrap your script in an onload event.

What's the difference between window onload vs document onload?

The general idea is that window. onload fires when the document's window is ready for presentation and document. onload fires when the DOM tree (built from the markup code within the document) is completed.


1 Answers

If you don't, then the onload method will be attributed to the current object, whatever that is (if any). So sometimes it may work, but writing window.onload is the most explicit, specific and safe way to do it.

like image 62
Otávio Décio Avatar answered Oct 04 '22 21:10

Otávio Décio