Tuesday, May 7, 2024
 Popular · Latest · Hot · Upcoming
101
rated 0 times [  106] [ 5]  / answers: 1 / hits: 21170  / 15 Years ago, thu, june 18, 2009, 12:00:00

I was reading a tutorial and the author mentioned to include JavaScript files near the closing body tag (</body>) in HTML.


For what type of functionality should I not declare/define JavaScript include in the head section? It makes sense to me include JavaScript like Google Analytics near the closing body tag. Where should I be careful in defining JavaScript include near the closing body tag?


More From » html

 Answers
76

It will often be argued that for speed purposes you should put script tags right at the end of the document (before the closing body tag). While this will result in the fastest page load, it has some serious downsides.


Firstly, a common idiom with Webpage development is to have a header file, a footer file and your content in the middle. To keep unnecessary JavaScript code to a minimum, you'll often want to put code snippets in individual pages.


If you include jQuery, for example, at the end of the document, your jQuery code snippets (like document ready stuff) must happen after that. That can be awkward from a development point of view.


Secondly, in my experience, because the page load is faster, you can end up noticing certain effects being applied because the page has already loaded by the time they are applied.


For example, if you put a table in a document and right before the body close tag put:


$(function() {
$("tr:nth-child(odd)").addClass("odd");
});

with appropriate styling, that effect being applied will often be visible. Personally I think that makes for a bad user experience potentially. I think often you're better off having the page load slightly slower (by putting scripts at the top) if you don't get disconcerting visual effects.


I generally advocate effective caching strategies so you only have to download JavaScript files when they change, as in Supercharging JavaScript in PHP (but the principles apply to any language, not just PHP) and still putting scripts at the top. It's far more convenient.


[#99286] Monday, June 15, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
blaisep

Total Points: 748
Total Questions: 95
Total Answers: 108

Location: Federated States of Micronesia
Member since Sun, May 16, 2021
3 Years ago
blaisep questions
Wed, Dec 16, 20, 00:00, 3 Years ago
Sun, Aug 16, 20, 00:00, 4 Years ago
Tue, Nov 12, 19, 00:00, 5 Years ago
Mon, Nov 11, 19, 00:00, 5 Years ago
;