J_men
J_men

Reputation: 387

Why wait for window.onload?

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

Answers (4)

ne1410s
ne1410s

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

wpiekutowski
wpiekutowski

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

gaelgillard
gaelgillard

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

Paul S.
Paul S.

Reputation: 66314

In what situations in javascript do we need to wait for the window onload event before running code?

  • If you want to access nodes in the #document
  • If you want to get values such as the height or width of the page
  • If you want to avoid race conditions when appending new things to the #document
  • Basically, everything DOM related to the specific page

And what useful things can be done without needing to wait?

  • Computational actions
  • Declaring functions, initialising variables
  • Testing feature support, including polyfills
  • Basically, everything non-DOM related, or DOM related to the specific browser but not the page

Upvotes: 3

Related Questions