Open In App

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

Improve
Improve
Like Article
Like
Save
Share
Report

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:

  • We can do this by using the jQuery ready() function.
  • Create an HTML page and use the <script> tag which specify the src to embed the above jQuery CDN link.
  • In ready() method, write the function which need to be prevented form execution before the entire document loads.

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.

HTML




<!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:

Function is used to prevent code from running


Last Updated : 30 Dec, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads