What is the difference between $(document).ready() and $(window).on('load')?
Quick Answer
$(document).ready() (or the shorthand $(function(){})) fires when the DOM is parsed and ready to manipulate — it doesn't wait for images/stylesheets. $(window).on('load') fires later, after everything including images and iframes has finished loading.
$(document).ready runs as soon as the HTML is parsed and the DOM is usable — it doesn't wait for images or CSS files to download. $(window).on('load') waits for absolutely everything, including images. So 99% of the time I use ready, or its shorthand where you just pass a function to $(), because I want to wire up event handlers and init components as early as possible. load is only for when I need an image's real height or the fully painted layout.
- Use
readyfor almost everything — attach handlers, initialise widgets. - Use
loadonly when you need final dimensions of images or a fully rendered layout. - Native equivalents:
DOMContentLoadedand theloadevent. A<script defer>at the end of<body>often removes the need forreadyentirely.