Reputation: 387
In what situations in javascript do we need to wait for the window onload event before running code?
And what useful things can be done without needing to wait?
Upvotes: 0
Views: 1148
Reputation: 7082
From a related SO post: window.onload vs. body.onload vs. document.onready
window.onload waits until all assets have finished downloading, such as images and scripts.
There is also a "DOM ready" event that allows quicker access to the dom, as it only waits until you can access the DOM via the API.
Upvotes: 1
Reputation: 46
You need to use window onload event before running code when your code needs to access/modify DOM and all the assets (images, fonts, etc). You might also use jQuery's (or equivalent) &(document).ready()
. It fires earlier than window onload, so users will feel like website loads faster. The difference is that on document ready only DOM tree is ready, but assets might not be loaded yet. On window onload, everything's already loaded.
Before document ready event, you might still do some stuff. For example, if you need to create some kind of a unique id for a user and set a cookie, there's no need to wait for DOM. Or if you want to do something based on cookies (provided it doesn't touch DOM). Or you need to load some external data from an API (but you need to wait for DOM before trying to display that data). In general, anything that doesn't touch DOM should be ok.
Upvotes: 1
Reputation: 2523
If your code need other files to be executed (like libraries, frameworks or your own file that expose global things), you should always wait that the browser had finished to download everything.
So in most case, you should do this. You could find edges cases that don't need this but it's very rare and it doesn't cost you very much in a human perception of time.
Upvotes: 0
Reputation: 66314
In what situations in javascript do we need to wait for the window onload event before running code?
And what useful things can be done without needing to wait?
Upvotes: 3