Google's Closure Compiler can shrink JavaScript files using a variety of methods such as removing comments, spaces and renaming variables with shorter names. This can mean quicker downloads and faster start-up. The Closure Compiler can also be used to find errors in your programs, adds type checking and (in some cases) can make them faster by inlining functions and other methods!
This guide gives a basic run through on how to install and use it!
The compiler set up pages mention needing Java 7, I use Java 11 and everything seems to work okay. If you need help installing Java, click the link for a Java install guide.
After downloading the Closure Compiler, to simplify things, I renamed it as compiler.jar and put it in an easy to get to location, in my case c:\temp
To use the compiler the basic format is:
java -jar c:\temp\compiler.jar --js infile.js --js_output_file outfile.js
The bits in bold may need to be changed depending on where the compiler is and what your files are called.
Using Closure and applying the above method to the source for the Pathfinder activity as follows:
java -jar c:\temp\compiler.jar --js trak.js --js_output_file compiled.js
The above creates a compressed file called 'compiled.js'. In this example, the file size was reduced from 59KB to 33KB! Nearly half the size! A faster download for very little effort!
The compiler also has the option for more advanced optimisations, enabled by adding the following:
java -jar c:\temp\compiler.jar --js infile.js --compilation_level ADVANCED_OPTIMIZATIONS --js_output_file outfile.js
This option uses more aggressive means to compress the JavaScript file and can inline functions for improved speed. So far this has failed to work on any of my programs but this mode also does more code checking and can highlight errors. I use this mode to find fixable errors (it found a duplicate function in one of my programs!) and then upload the default optimised version.
By using special comments, you can help the compiler spot errors in your code. The example below shows how you would tell the compiler that the following variable is a boolean (true/false) type.
/** @type{boolean} */
let done=false;
If later you assigned a number to the variable (e.g. done=1), you would get a warning similar to this:
WARNING - [JSC_TYPE_MISMATCH] assignment found : number required: boolean 123| done=1; ^^^^^^
There are a lot more annotations available but the above seems like one of the most useful.
The Closure Compiler is definitely worth looking at, it improves download speed finds errors with minimal effort. Microsoft have even used it to improve the performance of Office Online/365!
Created
(28/10/2024)