March
29th, 2008
When to embed your JavaScript
By now we should all know the benefits of including your JavaScript as external files. But does that mean we should always include them that way? The primary benefit of external JavaScript files is that the browser should cache them. So when someone comes to your home page and downloads yourfile.js it’s stored locally on the user’s computer. As they click through other pages on your site which include the same yourfile.js file then it’s pulled from cache. Subsequent page requests are sped up for two reasons.
- The document size is smaller since it does not embed the JavaScript
- Including the javascript is done from cache and doesn’t incur any network latency or dns resolution
Sounds good, right? It’s great. But there are certain cases when it makes sense to embed your JavaScript. If you have a page which receives a large percentage of your traffic then that page’s performance should be treated as a special case scenario. Lets say your home page receives 75% of all the traffic your site gets. If you can increase it’s performance by 50% ten you’ve essentially increased your site’s overall performance by 37.5%. That’s significant enough that you’ll want to have a look at it. Below is a great example of the cost of external javascript files (1.07 seconds is a lot).

Embedding your JavaScript won’t gain you a 50% increase in performance but it’s one of many tricks you can use. By embedding your Javascript you can avoid a few performance penalties.
- The browser doesn’t have to initiate an extra http request
- Depending on your site the browser won’t need to wait for the JavaScript file to load before moving on to doing other more important things (from the user’s perspective - like loading a photo)
Don’t go embedding JavaScript on your home page at random. You definitely need to know the pros and cons of making the change. Even then it’s only going to make a difference if you have enough traffic to warrant the change.
Additional resources.
