In JavaScript, when I want to run a script once when the page has loaded, should I use window.onload
or just write the script?
For example, if I want to
The reason for waiting for the DOM to be loaded is so that you can target any elements that load after your script. If you're just creating an alert
, it doesn't matter. Let's say, however, you were targeting a div
that was in your markup after your script, you would get an error if you don't wait until that piece of the DOM tree to load.
document.ready
is a great alternative to window.onload
if you're using jQuery.
See here: window.onload vs $(document).ready()