Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
140 views
in Technique[技术] by (71.8m points)

html - Where should I declare JavaScript files used in my page? In <head></head> or near </body>?

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

I was wondering for what type of functionality I should 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?

question from:https://stackoverflow.com/questions/1013112/where-should-i-declare-javascript-files-used-in-my-page-in-head-head-or-nea

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It will often be argued that for speed purposes you should put script tags right at the end of the document (before the close 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 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...