1

I'm currently learning jQuery after finishing JavaScript course. The document says that the ready method waits until DOM finished loading. However, I have 2 points I'm curious about. 1) Since the script tag are usually added at the end of the body tag, shouldn't the DOM already finished loading anyway without the ready method. 2) If we need the ready method in jQuery, why do we not need it when writing usual JavaScript too?

  • Possible duplicate of [What is the non-jQuery equivalent of '$(document).ready()'?](https://stackoverflow.com/questions/2304941/what-is-the-non-jquery-equivalent-of-document-ready) – Atul Sharma Mar 11 '19 at 07:10

1 Answers1

3

1) Since the script tag are usually added at the end of the body tag, shouldn't the DOM already finished loading anyway without the ready method.

Yes you are right, if script tag is added add the end of the body, you do not need to wrap your code with $(document).ready() as the DOM elements are already available to use in the code.

2) If we need the ready method in jQuery, why do we not need it when writing usual JavaScript too?

The jQuery equivalent of $(document).ready() is DOMContentLoaded

The DOMContentLoaded event fires when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading.

Please Note: You can also use script defer attribute

This Boolean attribute is set to indicate to a browser that the script is meant to be executed after the document has been parsed, but before firing DOMContentLoaded.

Mamun
  • 58,653
  • 9
  • 33
  • 46
  • nit-picking, scripts with the `defer` attribute will get executed after all the DOM is parsed, but before DOMContentLoaded fired, so if you are in an inline script at the bottom of the page and need some deferred script to have fired, then you still have to wait for DOMContentLoaded. – Kaiido Mar 11 '19 at 07:18
  • @Kaiido, you are right...mentioned that in the updated the answer:) – Mamun Mar 11 '19 at 07:25