Reputation: 415
If we call a javascript method myMethod()
in a script tag which is before closing body, is it equivalent to calling myMethod()
inside jQuery's document.ready function ? If not, Why ?
Upvotes: 6
Views: 821
Reputation:
Not exactly. $(document).ready();
reacts on the so called DOMContentLoaded
event which is fired right after the DOM has been loaded and the browser is aware of all the elements on the page (not the content itself).
The main reason why code is usually put inside these blocks is not that much related to preventing blocking of parallel loading but to ensure that the elements which are to be manipulated during page load are actually loaded and present in the DOM tree. Not much sense in manipulating elements which the browser is not aware of right?
Putting JavaScript content (or any other content for that matter) at the bottom of the page is actually more closely related to the onload
event which is fired after the page has finished loading, including the content itself. Either way its almost certain that content inside $(document).ready()
blocks will be executed before the one at the bottom of the page however if you load external libraries on which the code inside the ready()
block relies you can't put those at the bottom of the page.
In general if you have code that isn't dependent on external libraries and a successful loading of DOM you can safely put it at the bottom of the page. If you however have stuff that needs to be executed right after the DOM has been loaded you most definitely want that code in the $(document).ready()
block, but do have in mind that you can place that block wherever you want, even in the middle of the page (which can be a nice trick sometimes).
Upvotes: 0
Reputation: 50728
From here:
Under the hood: $(document).ready() As you would expect from John Resig, jQuery’s method for determining when the DOM is ready uses an assortment of optimizations. For example, if a browser supports the DOMContentLoaded event (as many non-IE browsers do), then it will fire on that event. However, IE can’t safely fire until the document’s readyState reaches “complete”, which is typically later. If none of those optimizations are available, window.onload will trigger the event.
These events are independent of a location within the HTML tag, as other event still are going on even at the time of rendering </body>
.
Upvotes: 6
Reputation: 76880
No it's not the same, you place the <script>
tags before the closing </body>
tag to avoid blocking the rendering of html on older browsers, AFAIK, but you have no guarantee that the DOM is "ready"
Upvotes: 3