As web pages become richer and more complex, from dynamic interface effects to loading content via AJAX, they can also become burdened with Javascript libraries which put more load on your network and degrade the user experience of your website.

There are two parts to speeding up JavaScript on your website. The first addresses how quickly your page loads, and the second how well it responds to the user. There are several things you can do to improve the former, while the latter is mostly at the mercy of the web browser’s Javascript engine.

When possible, combine multiple Javascript files into a single file which can be loaded once and cached by the web browser. Also consider using a Javascript minifier (or compressor) to reduce the code size. A minifier uses tricks like removing comments and extra whitespace and shortening some variable names to reduce the size of your script. Most minifiers are command-line tools, but there are several online tools as well. Alternatively, if your web server supports it, simply turn on gzip compression for Javascript files.

Placing Javascript files at the end of your web page improves apparent performance. For technical and historical reasons, when a browser loads a script, it stops loading other page elements until the script is resolved. Unless your script writes directly to the document or is required for inline code, moving it to the end lets the web browser load and render the rest of the web page (the part the user sees) as quickly as possible.

Finally, consider using Expires headers to instruct web clients to cache Javascript files for a long time. In Apache, this is easily achieved through the mod_expires instructions,

ExpiresActive On
ExpiresByType text/javascript "access plus 1 year"

If you need to retain the ability to change your Javascript files more frequently, add a version number to the filename and update it as necessary. For example, combined-1.0.js