Open In App

Which function is used to prevent code running before document loading in jQuery ?

In this article, we will learn how to prevent code from running, before the document is finished loading.

Sometimes we might need to run a script after the entire document gets loaded, for example, if we want to calculate the size of images in the document then we need to wait until the entire document gets loaded.



The ready() method is an inbuilt method in jQuery that executes the code when the whole page is loaded. This method specifies the function to execute when the DOM is fully loaded.

Syntax:



$(document).ready(function)

Parameters:  This method takes one function as an argument. It is used to specify the function to run after the document is loaded.

CDN link:

<script src=”https://code.jquery.com/jquery-1.9.1.min.js”></script>

Approach:

Example: In the below code, line 20 is in ready() method, so lines 19 and 25 are executed and printed in the console before line 20, The line 20 is executed after the entire document gets loaded.




<!DOCTYPE html>
<html lang="en">
  
<head>
    <script src=
    </script>
</head>
  
<body>
  
    <script>
        console.log("This is on line 19 ");
  
        $(document).ready(function () {
            console.log("this line will execute after"
            + " the webpage is loaded (on line 20)");
        });
  
        console.log("This is on line 25 ");
    </script>
</body>
  
</html>

Output:

Article Tags :