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.
Parameters: This method takes one function as an argument. It is used to specify the function to run after the document is loaded.
- 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.