jQuery: onload() Vs. $.ready()?
- $(document).ready() (or its shorthand $()) is a jQuery event that triggers when the DOM (Document Object Model) is fully parsed and ready for manipulation, even if external resources like images are still loading. This means it usually fires before the entire page, including images, has finished loading.
- $(document).ready() is often used when you want to manipulate the DOM or perform actions as soon as the DOM is ready but before all external resources have loaded. It's suitable for most cases where you want to work with the structure of the page.
In this example, "Document is ready." will be logged to the console as soon as the DOM is ready, even before the image (if any) has fully loaded.Example using body onload:
In this example, "Page is fully loaded." will be logged to the console only after the entire page, including the image, has loaded.
The key difference is in when the code is executed: $(document).ready() fires when the DOM is ready, while body onload fires when the entire page, including external resources, is fully loaded. The choice between them depends on your specific use case and whether you need to interact with resources that might not be ready when the DOM is parsed.