jQuery Document Ready Function
The browser reads a page from top to bottom. If your script runs before the HTML elements are created, jQuery cannot find them. The document ready function makes your code wait until the page structure (the DOM) is ready.
Syntax
$(document).ready(function () {
// your jQuery code here
});
// short form, the same thing
$(function () {
// your jQuery code here
});
The code inside runs when the DOM is ready. It does not wait for the images and other files to load.
Example
<p id="msg">Loading...</p>
$(function () {
$('#msg').text('The page is ready');
});
HTML after the code runs
<p id="msg">The page is ready</p>
What happens without ready?
If the script is in the head, before the element exists, the selector finds nothing and does nothing. There is no error, so it is a common bug.
<script>
$('#msg').text('Hello'); // the element does not exist yet, so nothing happens
</script>
<p id="msg"></p>
Ready vs window load
| $(document).ready() | $(window).on(‘load’) |
|---|---|
| Runs when the HTML is parsed (DOM ready) | Runs when everything is loaded: images, styles, frames |
| Earlier, so the page feels fast | Later |
| Use it for most jQuery code | Use it when you need image sizes |
$(window).on('load', function () {
console.log('All files are loaded');
});
You can use ready many times
<p id="log"></p>
var order = [];
$(function () { order.push('first'); });
$(function () { order.push('second'); });
setTimeout(function () { console.log(order.join(', ')); }, 50);
Console output
first, second
The functions run in the same order in which you wrote them.
Passing $ safely
This form is a nice habit when you also use another library which uses the $. Inside the function, $ is always jQuery:
jQuery(function ($) {
// $ is jQuery here
});
Note:
If your script is at the end of the body, the elements are already there. Many people still use the ready function to be safe. Next: jQuery Selectors.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |