33

Possible Duplicate:
jquery - Is $(document).ready necessary?

Putting the JS just above the </body> tag improves perceived load time because the browser doesn't have to read and parse through all the JS before it can start rendering the page.

But it has another benefit, doesn't it? We don't need to wrap the JS in $(document).ready(function() { ... }) because all the elements are already above the JS and thus are ready for manipulation.

  1. Is $(document).ready necessary to ensure the DOM has fully loaded and is ready for manipulation?

  2. Is there any difference between the execution times? Would one method fire faster than the other?

  3. Could we link our external JS files (<script src="..." />) at the bottom of the page too then, or does that need to be in the header?

0

1 Answer 1

22

This SO answer says NO:

stackoveflow question

$(document).ready is for assurance full DOM is available at the time the function is called. Any functions and events not depending on the DOM don't need to be put into the ready event.

Also - to improve page rendering speed - load javascript files dynamically in non-blocking fashion: http://berklee.github.com/nbl/ or https://github.com/rgrove/lazyload/

This technique works somewhat like this:

 var script = document.createElement("script");
 script.type = "text/javascript";
 script.src = "file1.js";
 document.getElementsByTagName("head")[0].appendChild(script);

This new element loads the source file file1.js. The file begins downloading as soon as the element is added to the page. The important thing about this technique is that the file is downloaded and executed without blocking other page processes, regardless of where the download is initiated. You can even place this code in the header of a document without affecting the rest of the page (aside from the one HTTP connection that is used to download the file).

this book: "High Performance JavaScript" by Nickolas Zakas has a lot of interesting information about JavaScript performace optimization.

1
  • I still do not know why loading js dynamically is non-blocking but the other way causes blocking ?
    – thelonglqd
    Oct 23, 2020 at 9:50

Not the answer you're looking for? Browse other questions tagged or ask your own question.