JavaScript Optimization: Get Outta My Head!

The most common mistake people make with JavaScript is improper placement within the HTML document.

For years, people (and especially WordPress developers) grew accustomed to including JavaScript files in the document <head>. Unfortunately, there is one huge problem with this technique:

When a web browser renders an HTML document, it must first parse—and then load completely—the contents of the <head> before it can show any content whatsoever!

Therefore, if you’re calling JavaScripts in your document <head>, you’re forcing web browsers to load those scripts entirely before serving any content to the user. Egregious, indeed.

So, what’s a webmaster to do? Follow the rule below to ensure proper JS positioning on your site.

All JavaScript should be placed just before the closing <body> tag, but with two notable exceptions: Google Analytics and TypeKit scripts, which we’ll address separately.

Google Analytics tracking code

In 2010, Google introduced a new, asynchronous tracking code for Analytics users. Because this script loads asynchronously (and therefore does not affect the perceived page load time), it can be referenced from a different, perhaps more optimal, location in the HTML document.

For best results, Google recommends that you place this new, asynchronous tracking code just after the opening <body> tag in your document.

TypeKit activation script

TypeKit uses JavaScript to serve commercial fonts to sites all over the web. In order to prevent an unsavory “flash of unstyled text” (FOUT), this script should be loaded in the document <head> to ensure that the font is available the second the browser serves content to the user.

Next: Plugins: Proceed with Caution! »