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 ?
jQuery $(document). ready() Equivalent in JavaScript This event fires when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading.
Scripts can be placed in the <body> , or in the <head> section of an HTML page, or in both.
$(document). ready is javascript code, so it has to be written in <script> element and after jQuery is loaded. If you don't write $(document). ready , your code will not wait for DOM to load completely and execute the javascript code immediately.
The <script> tag can be placed in the <head> section of your HTML or in the <body> section, depending on when you want the JavaScript to load. Generally, JavaScript code can go inside of the document <head> section in order to keep them contained and out of the main content of your HTML document.
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>
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With