Doug Null
Doug Null

Reputation: 8327

Where to place JavaScript functions: <head>? <body>? or, after </html>?

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

Upvotes: 9

Views: 14066

Answers (3)

JKirchartz
JKirchartz

Reputation: 18022

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.

Upvotes: 13

folktrash
folktrash

Reputation: 186

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.

Upvotes: 1

George Cummins
George Cummins

Reputation: 28906

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

Upvotes: 1

Related Questions