How to minify JavaScript
When you minify your JavaScript you will improve your sites Page Speed.
In this tutorial, we are going to look at how to minify JavaScript. We will cover:
Minify JavaScript Recap
You may have noticed that sometimes there are two versions of JavaScript. For example, JQuery (a popular javascript library) has a production version and a development version.
The production version comes in at 19KB. The development version which is the same code is 120KB.
100KB larger! Many people make the mistake of adding the development version on their website.
Why is the production file smaller?
To make a production JavaScript file you are making the file smaller by minifiying it. This is:
- Removing whitespaces such as spaces and tabs
- Renaming code to make it smaller by removing variables and function names
- Removing comments which help developers understand the code
Once we minify JavaScript it is no longer easy to read by developers and is much smaller in size. It goes from looking like this:
/*!
* jQuery JavaScript Library v1.10.2
* http://jquery.com/
*
* Includes Sizzle.js
* http://sizzlejs.com/
*
* Copyright 2005, 2013 jQuery Foundation, Inc. and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2013-07-03T13:48Z
*/
(function( window, undefined ) {
var
// The deferred used on DOM ready
readyList,
// A central reference to the root jQuery(document)
rootjQuery,
// Support: IE<10
// For `typeof xmlNode.method` instead of `xmlNode.method !== undefined`
core_strundefined = typeof undefined,
// Use the correct document accordingly with window argument (sandbox)
location = window.location,
document = window.document,
docElem = document.documentElement,
...
To looking like this:
*! jQuery v1.10.2 | (c) 2005, 2013 jQuery Foundation, Inc. | jquery.org/license
//@ sourceMappingURL=jquery-1.10.2.min.map
*/
(function(e,t){var n,r,i=typeof t,o=e.location,a=e.document,s=a.documentElement,l=e.jQuery,u=e.$,c={},p=[],f="1.10.2",d=p.concat,h=p.push,g=p.slice,m=p.indexOf,y=c.toString,v=c.hasOwnProperty,b=f.trim,x=function(e,t){return new x.fn.init(e,t,r)},w=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,T=/\S+/g,C=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,N=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,k=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,E=/^[\],:{}\s]*$/,S=/(?:^|:|,)(?:\s*\[)+/g,A=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,j=/"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g,D=/^-ms-/,L=/-([\da-z])/gi,H=function(e,t){return t.toUpperCase()},q=function(e){(a.addEventListener||"load"===e.type||"complete"===a.readyState)&&(_(),x.ready())},...
Believe it or not, this is the same code that acts in the same way. Developers can read the first version. The second version is to improve performance.
And it is this minified javascript you should always use on your website.
Why should I minify JavaScript
The main reason is Page Speed. The smaller the JavaScript files on your website the faster they will load.
A minified version of the file will be much quicker to load than the development version. Let's take a look at an example.
When looking at Trader Joes from Chrome we can inspect the network tab and see which files have downloaded.
One of these files is JQuery.
The file is being loaded from the JQuery CDN. This means that the file will download fast but the file is not minified. This is the URL:
https://code.jquery.com/jquery-1.10.2.js
As the file is not minified it is large and comes in at 278KB. This is the developer version of the file, not the one you want to use on a production website.
We can fix this and switch to the minified version. This is because JQuery CDN already has the minified version of the file. To load the minified version all Trader Joes needs to do is change the URL from this:
https://code.jquery.com/jquery-1.10.2.js
To this:
https://code.jquery.com/jquery-1.10.2.min.js
Now the same file goes from 278KB to 90.9KB, saving 188KB. All we did was add ..min
to the JavaScript file. If you have 5 or 6 JavaScript files on your page the page speed improvement could be a few seconds.
Unfortunately, you are not always lucky enough to have a minified version of the file. When this happens you will need to create one yourself. Let's look at three ways you can do this.
How to Minify JavaScript
We are going to look at three common ways to minify JavaScript:
- Using a CDN
- Using an online minify tool
- Using a WordPress plugin
Let's start with a CDN.
How to minify JavaScript with a CDN
Some CDNs will minify the JavaScript files for you “on-the-fly”. This means they will read your JavaScript files and minify them if needed.
If they are not then it will create a minified version and cache it in their CDN.
One CDN that does this is CloudFlare.
You can use their automatic minify JavaScript and CSS feature. To enable it, go to the speed section of the control panel.
This is the first option in the list because a CDN will speed up your website in many ways including your TTFB.
Sometimes I am asked why is this better than a WordPress Plugin.
- CDNs have many advantages beyond minifying files. They send your website around the world making it faster to load (TTFB).
- WordPress plugins can slow down your website so be careful when installing a new one.
CDNs do tend to be more expensive, if you are on a budget then we can look at some free options.
How to minify JavaScript With an Online Tool
Before we dive into how you can minify your JavaScript files with this online tool, make sure that you do a backup. There are occasions where the minification can break the code and you need a way to get back the original.
With that warning out of the way, let's look at how you can minify JavaScript.
The online tool is UglifyJS. This website allows you to copy and paste your JavaScript into the box provided and hit Uglify.
Minification is sometimes called Uglify because it makes the JavaScript code look ugly!
Not to pick too much on Trader Joes but they also have a custom.js
file on their website. This file also needs minifying.
The script URL is:
https://www.traderjoes.com/scripts/custom.js
I checked to make sure that there was no minified file available by visiting the link:
https://www.traderjoes.com/scripts/custom.min.js
I got a 404 page which means “not found”.
Let's create a minified version using the UglifyJS tool, this is a five step process:
- Copy the JavaScript that you want to minify (In this example it will be custom.js)
- Open up the UglifyJS site
- Copy the JavaScript and it will minify here it is 45% smaller:
- Copy the minified JavaScript and save it to a new file custom.min.js
- You will then need to update the HTML to point at the new file like this:
<script src="https://www.traderjoes.com/scripts/custom.min.js"></script>
The last option is for WordPress users.
How to minify JavaScript for WordPress
The above method is fine for a one off minify task but what if you have many files that need minifying. Or maybe you just want to install a plugin and be done with it.
The optimize WordPress plugin I recommend is Autoptimize.
To install it:
- Download the zip file
- Then upload the zip file to your server and unzip it to the /wp-content/plugins/ folder
- Once unzipped you can activate the plugin in the “Plugins” menu
- When activated go to Settings > Autoptimize and then enable JavaScript Optimization
You may notice that you can also use this plugin to optimize the CSS on your page. This is because you can also minify CSS files.
This is one option with WordPress but not the only option. I want to repeat that this will speed your website up but it will come with the overhead of managing the plugin. I have seen WordPress sites get into trouble because there are too many plugins enabled.
Treat every plugin you add to your site with care. If you can afford it then buy a CDN.
Wrapping Up, How to minify JavaScript
We have looked at three methods for how to minify JavaScript:
- Using a CDN such as CloudFlare
- Using an online tool such as UglifyJS
- Using a WordPress Plugin like Autoptimize
My recommendation is to use a CDN. This will work whenever you add new JavaScript and unlike a plugin, it will not slow down your site.