Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is placing script tag before </body> tag equivalent to jQuery's document.ready method

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 ?

like image 979
furiabhavesh Avatar asked Apr 16 '12 11:04

furiabhavesh


People also ask

What is the equivalent of document ready in JavaScript?

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.

Can script tag be placed in body?

Scripts can be placed in the <body> , or in the <head> section of an HTML page, or in both.

Why should $( document ready normally be included at the start of a jQuery script?

$(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.

Where is the correct place to put the script tag?

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.


1 Answers

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>.

like image 103
Brian Mains Avatar answered Oct 17 '22 00:10

Brian Mains