9

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

Doug Null
  • 7,989
  • 15
  • 69
  • 148

3 Answers3

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.

JKirchartz
  • 17,612
  • 7
  • 60
  • 88
  • I don't know who downvoted you, but I upvoted to cancel it out because I agree with you generally – soniiic Mar 01 '12 at 17:04
  • thanks @soniic ... with such a generic question how can you not answer generally... – JKirchartz Mar 01 '12 at 17:32
  • So, to summarize the 3 answers so far: It is okay to put javascript within head & /head, and within body & /body. I had some of mine after /html. Yikes. – Doug Null Mar 05 '12 at 22:02
1

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>.

George Cummins
  • 28,485
  • 8
  • 71
  • 90
1

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.

folktrash
  • 176
  • 1
  • 11