jQuery $( document ).ready()

A web page can’t be manipulated safely with jQuery until the document is “ready.”
As in the example below, the first code will work (see the result here):

<html>
<head>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"
        integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
</head>
<body>
    <ul>
        <li>Item 1</li>
        <li>Item 2</li>
        <li>Item 3</li>
    </ul>
    <script>
        $('ul li:first-child').css('color', 'red');
    </script>
</body>
</html>

But the following code will not work

<html>
<head>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"
        integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
    <script>
        $('ul li:first-child').css('color', 'red');
    </script>
</head>
<body>
    <ul>
        <li>Item 1</li>
        <li>Item 2</li>
        <li>Item 3</li>
    </ul>
</body>
</html>

The reason is that we try to work with the DOM before it loads.

We don’t have access to the <li> element, because the DOM is loading from top to bottom.

To place the jQuery code to the top, and to be functional, jQuery must wait until the DOM loads.

Code included inside $( document ).ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute.

When the document is ready we can pass as callback, an anonymous function.

<html>
<head>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"
        integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
    <script>
        $(document).ready(function () {
            $('ul li:first-child').css('color', 'red');
        });
    </script>
</head>
<body>
    <ul>
        <li>Item 1</li>
        <li>Item 2</li>
        <li>Item 3</li>
    </ul>
</body>
</html>

Also You can use the shorthand for $( document ).ready().

// Shorthand for $( document ).ready()
$(function() {
    console.log( "ready!" );
});

Leave a Comment

WebPedia.net