Why do we use $(document).ready() at the top of our script?



Many of you might be wondering that way do we always use our javascript inside $(document).ready() in this Post i will tell you why do we use it and what if we don't write our script inside $(document).ready() function

Many of you might be wondering that way do we always use our javascript inside $(document).ready() like:

$(document).ready(function(){ 

// script goes hear

});

You might have used your script without $(document).ready() function and it might worked fine but this is not a good practice. We always prefer to write our script inside $(document).ready() the reason of using like this is document.ready() function to make sure the script runs after the page’s HTML content gets loaded.

By Using document.ready() function our script will run after the HTML content of the page gets loaded let take a example to understand it in more better way suppose you want to make a web page in which the content with the p tag get faded out after 5 seconds.

In case if we don’t write our JavaScript inside $(document).ready() function the script will get executed as soon as our page is loaded and in case our page take 4 second to get loaded then content with p tag in the page will appear for just 1 second, what if our page take 5 second or more to get load in this case content with p tag in the page will not appear.
This problem can be overcome by using $(document).ready() function now in this case the Javascript will get executed after all the content of the HTML page gets loaded no matter how long HTML content take to load its content. For now content with p tag will fadeout in 5 second after the whole HTML content will get loaded. So the best way to write this code is

<script>
$(document).ready(function(){
        $("p").fadeOut(5000);
   });
</script>

Stay tuned for the PHP Magento, WordPress,JavaScript and Magento2 latest tutorial and updates, Hope you enjoyed reading, if you need the professional Magento Development / PHP we can help you, just Click on the Link and send me your requirements.

Please Like the Post on Facebook or Google+.