最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Where to place JavaScript functions: <head>? <body>? or, after <html>? - Stack Overflo

programmeradmin1浏览0评论

I'm confused about where to place JavaScript functions:

When should they be put within the head When inline within the body And, when after the closing html tag?

thanks

I'm confused about where to place JavaScript functions:

When should they be put within the head When inline within the body And, when after the closing html tag?

thanks

Share Improve this question asked Mar 1, 2012 at 16:37 Doug NullDoug Null 8,32717 gold badges77 silver badges168 bronze badges 3
  • 1 Duplicate of stackoverflow.com/questions/196702/… – jacktheripper Commented Mar 1, 2012 at 16:40
  • I've seen this question quite a few times, but I don't recall ever seeing "after </html>" as an option. – Brandon Commented Mar 1, 2012 at 16:41
  • I place it just after the closing body tag – Packet Tracer Commented Mar 1, 2012 at 16:43
Add a comment  | 

3 Answers 3

Reset to default 13

The rules are fast and loose on this, There is no right or wrong way only better and less-better. (well after the </html> is wrong)

Generally speaking, javascript in the head of the document might block rendering of the page until the file is loaded in some browsers *cough*IE*cough*. This is due to a limit of simultaneous connections. So some people put them before the closing html tag. You can use a library to asynchronously load the javascript to avoid this blocking.

If you're using a library, or checking for the DOM to be loaded before executing code there's really no issue of where it's placed. However if you're not doing that it's probably better to put it at the end.

Javascript can always be safely placed in the head to make the functionality available to the entire page. Note that this can block loading of the rest of the document, so if you are loading very large or external Javascript, you may wish to load them inline near the end of the body.

Javascript placed inline will become available when executed. This allows you to conditionally load JS when page elements are loaded.

Javascript should always be placed in the <head> or <body>, never after </html>.

I agree, never seen (nor could I recommend) after html. Also, as noted, blocking is the concern. What I often go with is one script reference in the head to yepnope (an async js loader and testing tid bit (now included with modernizr)), and a tiny block of inline js at the end of the body tag that loads a bootstrap js file.

In that file, I use another yepnope request to load other needed assets asynchronously, and kick off initialization methods.

I've also taken to putting my Google Analytics code in a final yepnope block, so that it's the last thing to load, even after the js app boots.

发布评论

评论列表(0)

  1. 暂无评论