Places the script tag before the </body> tag, equivalent to the jQuery document.ready method

If we call the javascript method myMethod() in the script tag that is in front of the closing body, is it equivalent to calling myMethod() inside jQuery document.ready? If not, why?

+6
source share
3 answers

From here :

Under the hood: $ (document) .ready () As you would expect from John Resig, the jQuerys method to determine when the DOM is ready uses an assortment of optimizations. For example, if the browser supports the DOMContentLoaded Event (as many browsers other than IE do), then it will fire at this event. However, IE cannot fire safely until the readyState documents reaches "full", usually later. If none of these optimizations are available, window.onload will raise an event.

These events are location-independent in the HTML tag, as another event still continues even during </body> rendering.

+6
source

No, this is not the same, you put <script> tags before the closing </body> to prevent html rendering blocking in older AFAIK browsers, but you have no guarantee that the DOM is β€œready”

+3
source

Not really. $(document).ready(); responds to the so-called DOMContentLoaded event, which is triggered immediately after the DOM loads, and the browser knows about all elements of the page (and not about the content itself).

The main reason code is usually placed inside these blocks is not so much related to preventing parallel loading blocking, but to ensure that the elements that should be processed during page loading are actually loaded and present in the DOM tree. Is there not much point in manipulating elements that the browser does not know about correctly?

The inclusion of JavaScript content (or any other content, for that matter) at the bottom of the page is actually more closely related to the onload , which fires after the page has finished loading, including the content itself. In any case, he is almost sure that the contents inside the $(document).ready() blocks will be executed to the bottom of the page, however, if you load external libraries that use code inside the ready() block, you don’t can put them at the bottom of the page.

In general, if you have code that is independent of external libraries and remote loading of the DOM, you can safely place it at the bottom of the page. If you have things to do right after loading the DOM, you definitely need this code in the $(document).ready() block, but keep in mind that you can place this block wherever you want, even in the middle of the page (sometimes it can be a nice trick).

0
source

Source: https://habr.com/ru/post/913314/


All Articles