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
354 views
in Technique[技术] by (71.8m points)

html - JavaScript in <head> or just before </body>?

I am about to embark on a new web project and I plan to put some JavaScripts in the <head> and also some before </body>, using the following scheme:

  1. Scripts that are essential for the UX of the page: in the <head>. As I've picked up perusing the web - scripts in the <head> is loaded before the page loads, so it would make sense to put scripts that are essential to the user experience there.

  2. Scripts that are non-essential to the design and UX (Google Analytics scripts etc.): before the </body>.

Is this a sensible approach?

Another approach would be to put all the scripts in the <head> and add defer attributes to the non-essential scripts. However, I read that older versions of Firefox don't pick up the defer attribute.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

I think a lot of developers run javascript just before the </body> so that it is ran after all the elements have been rendered.

However, if you organise your code correctly, the position on the page doesn't matter.

For example, when using jQuery, you can ensure the code isn't ran until the page and its elements are fully rendered by doing the following:

$(document).ready(function(){
   //Code here
});

Then the script reference can be put in the head tag.


Update - Script tags should be referenced just before </body>. This prevents render blocking while the scripts load and is much better for site perception speed.

No obtrusive javascript should be used when using this technique.


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

1.4m articles

1.4m replys

5 comments

56.9k users

...