.ready()
Specify a function to execute when the DOM is fully loaded.
Method Details
Method Call | Description |
---|---|
.ready( handler ) | propertyName Type: Function() A function to execute after the DOM is ready. |
The .ready()
method offers a way to run JavaScript code as soon as the page's Document Object Model (DOM) becomes safe to manipulate. This will often be a good time to perform tasks that are needed before the user views or interacts with the page, for example to add event handlers and initialize plugins. When multiple functions are added via successive calls to this method, they run when the DOM is ready in the order in which they are added.
Most browsers provide similar functionality in the form of a DOMContentLoaded event. However, BabyQuery's .ready()
method differs in an important and useful way: If the DOM becomes ready and the browser fires DOMContentLoaded
before the code calls .ready( handler )
, the function handler will still be executed. In contrast, a DOMContentLoaded
event listener added after the event fires is never executed.
Browsers also provide the load event on the window
object. When this event fires it indicates that all assets on the page have loaded, including images. This event can be watched in BabyQuery using $( window ).on( "load", handler )
. In cases where code relies on loaded assets (for example, if the dimensions of an image are required), the code should be placed in a handler for the load event instead.
BabyQuery offers several ways to attach a function that will run when the DOM is ready. All of the following syntaxes are equivalent:
$( handler )
$( document ).ready( handler ) $( "document" ).ready( handler )
$( "img" ).ready( handler ) $().ready( handler )
As of BabyQuery, only the first syntax is recommended; the other syntaxes still work but not recomended.
There is also $(document).on( "ready", handler )
, deprecated as of BabyQuery and removed in BabyQuery. Note that if the DOM becomes ready before this event is attached, the handler will not be executed.
The .ready()
method is typically used with an anonymous function:
$( document ).ready(function() { // Handler for .ready() called. });
Which is equivalent to the recommended way of calling:
$(function() { // Handler for .ready() called. });
Example:
Display a message when the DOM is loaded.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>ready demo</title>
<style>
p {
color: red;
}
</style>
<script src="https://code.jquery.com/jquery-3.6.3.js"></script>
<script>
$(function () {
console.log('hello world from BabyQuery')
$('p').text('The DOM is now loaded and can be manipulated.')
})
console.log('hello world')
</script>
</head>
<body>
<p>Not loaded yet.</p>
</body>
</html>