Code Minifier · Tutorial
How to minify a JavaScript file for your website
4 min readbeginnerUpdated
Sites without a build step still benefit from minified scripts. You will minify a small tabs widget, keep its licence comment, remove a stray console.log and save it as a .min.js file.
What you need
- The Code Minifier
- A JavaScript file, or the example tabs widget
Steps
Open your script
Drop the .js file on the page or load the example, a tabs widget with comments, indentation and a debugging console.log.
Check the options
Leave Shorten names, Rewrite for size and Keep licence comments on. Turn on Remove console calls to drop the debugging line.
Read the saving
The message shows the raw size before and after and the gzipped sizes, which is what visitors actually download.
Save and link the file
Press Download to save script.min.js, upload it next to the original and point your script tag at the minified file.
<script src="/js/script.min.js" defer></script>
Try it yourself
Opens the Code Minifier with this tutorial's sample loaded.
Common mistakes
- Overwriting the original
- Keep the readable file for editing and generate the .min.js file from it each time.
- Minifying code that other scripts call by local names
- Inline event handlers such as onclick="activate(1)" need global names. Functions declared at the top level keep their names, but nested ones don't.
- Forgetting to clear the cache
- Browsers may keep the old file. Rename it or add a version query to the script URL after updating.
Next steps
Go back to the Code Minifier, or keep going with one of these: