How To Minify JavaScript (and Why You Should)
Most users desire an elegant web browsing experience, and JavaScript has long been a favorite for developers to deliver this elevated experience.
However, JavaScript isn’t only there to make sites look nicer. It also directly influences the website’s performance and success. Speeding up a website or cutting down the page loading time — two concepts that are core to JavaScript development — are crucial factors for improving user experience.
If you’re looking to enhance your website’s performance within the shortest period, you need to get familiar with JavaScript minification. It will help you exclude all the unnecessary characters from your JavaScript source code without altering its functionality. What’s more, it’ll reduce your website’s loading time and bandwidth usage.
JavaScript minification can be tricky. In this article, we’ll chart a course to assist you in minifying your JavaScript code for WordPress and non-WordPress websites.
What Is JavaScript?
JavaScript is a text-oriented scripting language for creating interactive websites on both the client and server sides. It’s a simpler and less complex language to learn than most, which explains its widespread use.
Whereas HTML and CSS build a website’s structure, JavaScript adds complex features that bring interactivity to your website to engage the users. For example, JavaScript offers complex elements such as scrolling video jukebox, 2D/3D videos, and interactive maps.
Notably, web browsers can understand JavaScript. Hence, alongside HTML and CSS, it’s a proficient choice to pick if you’re interested in web development. If you need to create a highly interactive website that runs in all browsers without any obstruction, then JavaScript is the most dependable option you can employ.
What Is Code Minification?
Minification is also known as minimization. Code minification means optimizing code to save space, reduce page load times, and lower website bandwidth usage. However, the biggest concern is to minimize the code without altering the functionality.
Code minification is possible in all core programming technologies, including HTML, CSS, and — as we’re about to see — JavaScript. However, the process isn’t instantaneous. Some work goes into making code more compact while keeping it functional.
To minify JavaScript code, you must parse it, compress it, and get the output. Once it’s been minified, it should be almost unreadable to the naked eye. You’ve removed all the unnecessary white spaces, comments, newline characters, and everything that initially made the code legible.
You may have to make some further changes to the code, too — for example, inlining functions, removing block delimiters, using implicit conditionals, or rewriting local variables.
Unminified vs Minified JavaScript Code Examples
Let’s take a look at some sample code. This first block is regular, unminified JavaScript:
// program to check if the string is palindrome or not
function checkPalindrome(str) {
// find the length of a string
const len = string.length;
// loop through half of the string
for (let i = 0; i < len / 2; i++) {
// check if first and last string are same
if (string[i] !== string[len - 1 - i]) {
return 'It is not a palindrome';
}
}
return 'It is a palindrome';
}
// take input
const string = prompt('Enter a string: ');
// call the function
const value = checkPalindrome(string);
console.log(value);
Now, let’s see how that same code looks once it’s been minified:
function checkPalindrome(n){const t=string.length;for(let n=0;n<t/2;n++)
if(string[n]!==string[t-1-n])return"It is not a palindrome";return"It is a palindrome"}
const string=prompt("Enter a string: "), value=checkPalindrome(string);console.log(value);
As you can see, the second block of code is much smaller and more compact. That means it will load and render more quickly, reducing page load time and speeding up content.
Here, we have reduced 529 bytes to 324 bytes, gaining 205 bytes of free space and reducing the page load by almost 40%.
It’s like taking a 529-page book and condensing it into a 324-page book. Of course, a human would struggle to read it, but a machine would speed through it without a problem.
When connecting multiple JavaScript files into an individual minified file, code minification decreases the number of HTTP requests to the server. This also lowers the site’s bandwidth consumption. Moreover, code minification lessens the time for a script to run — all things that drive down your Time to First Byte (TTFB).
Why Should You Minify JavaScript Code?
While writing the initial code, most developers primarily focus on getting things done. On that road, they tend to use lots of comments, spacing, and variables to make the code more readable for others working with it in the future.
Despite being an excellent programming language, JavaScript impacts web pages by slowing them down. To regain space and improve your page load speed, you must minify the JavaScript code.
The minified version of JavaScript code can reduce the file size by as much as 30–90%. Consequently, JavaScript minification has become a familiar ritual for all developers.
Every major JavaScript Library developer (Angular, Bootstrap, and so on) provides a minified version of JavaScript for production deployment. And each one uses a min.js extension to indicate this.
Benefits of Minifying JavaScript Code
Here is a brief outline of the benefits you will achieve after employing JavaScript minification:
- Reduction of page load time
- Less bandwidth consumption of your website
- Lower script execution time
- Fewer HTTP requests to (and a lighter load on) the server
- Theft protection (minified or uglified versions are complicated to read and steal for reuse)
Difference Between JavaScript Minification, Uglification, and Compression
JavaScript minification, uglification, or compression are similar in their functionality. However, they have different purposes.
JavaScript uglification rewrites the code to make it less human-readable. The process removes the whitespace, semicolons, and comments while renaming variables and inline functions to make the code difficult to read.
JavaScript has a library called UglifyJS to uglify code automatically. It improves performance and decreases the readability to make the code secure and less appealing to thieves.
Compression is unlike minification or uglification. It uses a compression algorithm like GZIP to rewrite the code into a binary format, making it much smaller and quicker loading.
While minification means reducing the whitespaces and comments, completely uglifying a code transforms it into an unreadable form by changing the function names, variable names, etc. And compression rewrites the code in binary to reduce the file size.
Both minification and compression are reversible, which means you can turn back the code to its original form, but uglification is irreversible.
How To Minify JavaScript Code
You can minify your JavaScript code in a variety of ways. Each of these methods takes a distinct approach from the others.
It’s nearly impossible to minify all of the codes in large JavaScript files manually. Manually minifying JavaScript files is only possible for small files because it’s so time-intensive.
To begin the manual JavaScript minification process, you would open your JavaScript file in your favorite text editor and manually delete all the spaces one after one. It will take a few minutes to remove all of the spaces and comments that have been set for the JavaScript file. Some of these text editors may even support regular expressions, which could speed up the process significantly.
The other option is to install minification tools on your computer and use them from the command line. You’d have to select the file you want to minify and add it to the command line switch along with the destination file. Then the minifying tool would take care of the rest.
How To Minify JavaScript Manually: Top 5 Tools
Developers rely on several JavaScript minification tools to minify the code and achieve better performance. However, each developer has their individual preference and opts for a different tool. There are plenty of JavaScript minification tools out there, all of which have distinct qualities, so you’ll need to consider your choice carefully.
We aren’t listing these tools according to any ranking or category. We’ve only included the most effective and popular JavaScript minification tools.
Here are the best JavaScript minification tools that can help you enhance your web performance.
1. JSMin
JSMin is a dedicated command line JavaScript minification tool and library to minify the JavaScript code and make the code as lightweight as possible. Just install JSMin as a global script, and it will remove all the whitespaces and unnecessary comments from the code very effectively. As a result, it can instantly reduce your JavaScript file size by around 50%.
So, the reduced size will give opportunities for quick downloads. You’ll also notice an increase in more communicative programming style as the cost of downloading new, literary self-documents.
However, JSMin has one drawback it doesn’t yield optimal savings. Because of its simplistic algorithm, it leaves many line feed characters unchanged. Otherwise, it may introduce new bugs in the code.
2. Microsoft Ajax Minify
Microsoft Ajax Minifier empowers you to improve the performance of your web applications by reducing the size of both JavaScript and CSS files. It deletes the comments, unnecessary space, semicolons, functions, and parentheses.
Besides shortening the local variables, function names, quotation/ double quotation, combining adjacent variable declarations, deletes the not executed codes.
With AjaxMin, you can analyze productivity and charge the JS minifier in the background. And, when it completes the minification, you can open up the productivity folder.
3. Google Closure Compiler
Google Closure Compiler is another excellent JavaScript minification tool. It formulates JavaScript for fast downloading and smoother performance. It also verifies the syntax and changeable suggestions, removes the dead code and types, and notifies you regarding JavaScript drawbacks. This tool gathers your JavaScript, evaluates it, removes redundant code, and rewrites it.
Also, it provides warnings for illegal JavaScript and potentially dangerous operations. Moreover, it’s a proper compiler from regular JavaScript to a better and minified JavaScript.
4. YUI Compressor
YUI compressor is a command-line JavaScript and CSS minification tool that assures you a higher compression ratio than most others. It’s a minification tool written in Java and relies on Rhino to tokenize the source JavaScript file.
Firstly, YUI examines the source JavaScript file to determine its construction. Then it prints out the token stream. Then, it removes as many white space characters as possible and replaces all local symbols with a 1 (or 2, or 3) letter symbol.
As the YUI Compressor is open-source, you can examine the source code to learn how it works. In addition, YUI is the most secure JavaScript minification tool with an eloquent compression ratio.
5. UglifyJS
UglifyJS is one of the most popular JavaScript minification tools. It can parse, minify and compress JavaScript code. Besides, the tool generates a source map file while compressing to track back to your original code.
Also, it can take multiple input files simultaneously, parsing the input files first, then parsing the options.
UglifyJS parse input files in order and apply any compression options. The files are parsed in the same global scope, which means that a reference from one file to a variable/function declared in another file will be matched appropriately.
How to Minify JavaScript Automatically: Top 5 Online Tools
There is an abundance of online JavaScript minifiers to compress your code online. Almost all online JavaScript minification tools follow a similar minification process.
First, you’ll copy and paste your JavaScript source code or upload the source code file on the tool. Then, you’ll optimize the minification tool’s settings to get a specific requirement-based output if options are available.
Finally, you’ll take that minified file and use it on the website instead of the original, expanded code (though you should keep the original source code file in safekeeping, just in case).
Here are 5 of the best online JavaScript Minification tools that can help you enrich your web performance. While we aren’t listing these tools in any particular order or category, we’ve only included the most popular and effective JavaScript minification solutions.
1. Toptal JavaScript Minifier
The Toptal JavaScript Minifier offers an efficient yet straightforward online JavaScript minifier where you can condense your JavaScript within a few seconds. It also allows you to convert the code to a .js file for future use.
2. JSCompress
JSCompress can minify and reduce the size of your JavaScript by 80%. It offers a simple click-and-go interface where you can either paste your code or upload your .js file for minification. You will receive the minified output as clean, copyable code rather than a .js file. Notably, the tool uses UglifyJS and Babel-minify to minify and compress JavaScript.
3. Minifier.org
Minfier.org is one of the most simplistic JavaScript minifiers you can utilize to minify your codes. It uses multiple methods to minify JavaScript code. The tool weights the size of your JavaScript code both before and after the minification. Then it calculates the gain of the script after the minification and displays it on the screen.
4. TutorialsPoint Online JavaScript Minifier
You can input a .js file, provide an URL or directly paste your raw code to the TutorialsPoint JavaScript minifier tool. The tool has an editable field to code directly if you wish. In addition, it has a single click minification option, and you can download the minified code in a .js file.
5. Packer: Dean Edwards JavaScript Compressor
If you need to compress your JavaScript code, the Packer by Dean Edwards could provide you with one of the most satisfactory online JavaScript compression experiences. It works with JavaScript tokens/atoms, and bit and byte patterns.
Besides, it lets you implement Base62 encode and Shrink variables option while minifying your code. To minify your JS code, copy and paste it into JavaScript and press the pack button. It will automatically generate minified code for you.
How to Minify JavaScript in WordPress: Top 5 Tools and Plugins
JavaScript minification follows a different procedure in WordPress. Minifying JavaScript requires either host support or installing a WordPress plugin. After installing a WordPress minification plugin, it’ll take care of the minification process for you.
There are numerous JavaScript minification WordPress plugins. Most of these plugins follow the same procedure for minifying and can be run from the WordPress dashboard.
Let’s explore some of the most effective tools for JavaScript modification in WordPress:
1. Code Minification in MyKinsta
If you’re a Kinsta customer, you can use our Code minification feature to minify your site’s JS and CSS files. All you have to do is enable Kinsta CDN and tick a couple of checkboxes in your MyKinsta dashboard. You don’t have to install any third-party plugins — your files will now be minimized.
This minification occurs on Cloudflare’s edge network, which also powers Kinsta CDN. All your minified files are also cached on Cloudflare’s network, translating into additional performance benefits.
2. W3 Total Cache
W3 Total Cache lets you minify JavaScript, CSS, and HTML with granular control. Besides, it allows you to minify inline, embedded, or any third-party JavaScript or CSS code. It also defers JavaScript and CSS for faster page loading, apart from minification. Moreover, the plugins offer multiple JavaScript minification opportunities for WordPress websites.
3. WP-Optimize
WP-Optimize is a WordPress optimization plugin that offers an advanced minification tool to minify CSS and JavaScript alongside clearing cache and optimizing your WordPress website. Also, it empowers you to defer CSS and JavaScript. As a result, the site loads the non-critical assets after the main page load, improving page performance.
4. Autoptimize
Autoptimize is a WordPress minification plugin that aggregates, minifies, and caches non aggregated CSS and JavaScript to reduce page load time and improve the performance of your website. It can minify and cache the scripts, inline the critical JavaScript, and async the non aggregated JavaScript.
If you are looking forward to a WordPress JavaScript minification plugin that will primarily focus on your website’s performance, Autoptimize is an excellent choice.
5. Fast Velocity Minify
Fast Velocity Minify offers advanced JavaScript, CSS, and HTML minification for WordPress users. It does the minification on the frontend when the first uncached request happens. Besides, the plugin has got a straightforward user interface and simple usability.
Summary
Gaining the ultimate performance from your web page requires attention to minor details. Thus, minifying HTML, CSS, and JavaScript enter your website performance to-do list.
We’ve explored numerous tools and plugins that can assist you in JavaScript minification. However, each mentioned tool or plugin serves the same purpose and operates efficiently.
Based on your use case, select a tool from this list and start minifying your JavaScript code for faster website performance.
Have we missed any JavaScript minification tool or WordPress minification plugin you like? Let us know in the comments section!
The post How To Minify JavaScript (and Why You Should) appeared first on Kinsta®.
版权声明:
作者:zhangchen
链接:https://www.techfm.club/p/30444.html
来源:TechFM
文章版权归作者所有,未经允许请勿转载。
共有 0 条评论