Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialMayank Srivastava
1,989 PointsHow does including jQuery just before end body tag make it faster?
One one hand, the ready method executes as soon as the DOM hierarchy has been fully loaded/constructed. And on the other hand, if you include the jQuery script tag just before the end body tag, it will still wait for the DOM to be fully constructed and then execute. So how is the latter faster than the former?
2 Answers
Marcus Parsons
15,719 PointsHey Mayank,
What happens is that when you include your code in the head of the document and wrap it in a $(document).ready(function() {});
function, the compiler looks at that jquery code and has to analyze that the code should not be executed until the document is fully loaded, then proceeds to load the document, and finally executes the code.
If, however, you just include it at the very bottom of the page, you skip that very first step of having the JS compiler analyze the code to see that it shouldn't be executed until the document is loaded. There are fewer steps for the compiler when including the script at the end instead of wrapping it in that function which makes it faster. Does that make sense?
Here is a performance test based on document.ready: http://jsperf.com/docready-vs-ending-script
gérald christophe
2,387 PointsHello,
I am interested in Mayank's question but I am a little bit confused by your answer.
If " the ready method executes as soon as the DOM hierarchy has been fully loaded" (as Mayank said) why does the " compiler looks at that jquery code and has to analyze that the code should not be executed until the document is fully loaded" (as you said). Does it means that depending on the elements manipulated in the function, the ready can be executed before the document is fully loaded?
Therefore it is "ready" not because the DOM is fully loaded but "ready" because the elements targeted by the function are actually loaded ?
Mayank Srivastava
1,989 PointsMayank Srivastava
1,989 PointsThank you for explaining it so well.
Marcus Parsons
15,719 PointsMarcus Parsons
15,719 PointsYou are very welcome, Mayank!