Moving your script tags: The quickest way to improve site performance

June 29, 2009
Development

At this point almost every web developer is familiar with YSlow. If you're not, YSlow is a Firefox extension that integrates with Firebug that analyzes the performance of webpages based on a set of rules Yahoo! has developed. By following this set of rules, you can make your website load much faster for visitors.

While working on the new NMC website, I ran YSlow and began making improvements. What I found shocked me. Perhaps the greatest gain in performance came from the easiest rule to implement:

Put Scripts at the Bottom

That's right, moving your script tags from the site header to immediately before the closing body tag can dramatically improve your site's performance. As an added bonus, this can almost always be done naively if you're using a modern javascript framework like jQuery.

So why does this work? When a browser downloads a site, it first works on the html and encounters additional components like stylesheets, scripts and images. If it can, it will download this in parallel. However, in all browsers (not just IE!), loading external scripts is blocking. The browser will not begin downloading anything new if a script is being downloaded. You can see this in effect by looking at Firebug's Net tab:

Before:

After:

As you can see, the blocking effect is dramatic. It is certainly worth moving your script tags to the bottom of your page if you can and also look into the other tips Yahoo! has.

Issues to look out for

  • document.write - If you're using document.write to insert content in place, moving your scripts will be an issue. That said, this generally isn't the preferred way of modifying content using a javascript framework so it is not often an issue with newer sites.
  • Timing/Appearance - If your scripts are doing any appearance manipulation to your site, you should be aware that putting them at the bottom will cause them to load later. This could make the loading process jarring for visitors.

Leave the first comment