Skip to content
Related Articles

Related Articles

What is the use of ready() function in jQuery ?

Improve Article
Save Article
Like Article
  • Last Updated : 28 Nov, 2021

In this article, we will see how to use ready() function provided by the jQuery library. The ready() function is used to execute some javascript code only when the HTML DOM is fully loaded. We should not manipulate the DOM until it is fully loaded. ready() method comes very handy to detect when the DOM is loaded successfully.

Syntax:

$(selector).ready(handler)

Here ‘handler’ is a JavaScript Function that is to be executed once the DOM is ready. The selector inside the parentheses doesn’t matter. For example, the three syntaxes below mean the same thing.

Example: In the below example, we are changing the text of h1 to “DOM is now ready” with the help of the ready() function which is firing when DOM is fully loaded.

HTML




<!DOCTYPE html>
<html>
  
<head>
    <script src=
    </script>
</head>
  
<body>
    <h1></h1>
    <script>
        $.holdReady(true);
        setTimeout(() => {
            $.holdReady(false);
        }, 2000);
        function onDOMReady() {
            $().ready(() => {
                $("h1").text("DOM is now ready");
            });
        }
        onDOMReady();
    </script>
</body>
  
</html>

Output: Here we are using holdReady() function to hold the DOM ready event for 2 seconds, so that we can simulate the delay in DOM load for testing ready() function.

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!