gzip compression will reduce identical strings to a byte or two. Use that and it's a non-issue. :)

Answer from Dagg Nabbit on Stack Overflow
🌐
GitHub
gist.github.com › daltonmenezes › 6b2c30805b213d28a9e9c51db224d1ae
A function to minify strings in JavaScript. · GitHub
A function to minify strings in JavaScript. GitHub Gist: instantly share code, notes, and snippets.
🌐
Kinsta®
kinsta.com › home › resource center › blog › javascript tutorials › how to minify javascript — recommended tools and methods
How to minify JavaScript — Recommended tools and methods
July 31, 2024 - 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. 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);
People also ask

What is JavaScript Minification?
Minification, or minimization, of JavaScript source code is the process removing all characters that aren't required for proper execution. These unnecessary characters usually include formatting characters, like: whitespaces, linebreak characters, comments, and in some cases block delimeters and end-of-line characters. After minification is applied, JS code is supposed to keep its functionality.
🌐
minify-js.com
minify-js.com
Minify JS Online. JavaScript Minification tool that works in browser.
How does JavaScript Minification work?
Minification process is performed by a software or utility that analyzes and rewrites source code to reduce its size. Usually, minification process includes removal of whitespaces, shortening of variable names, and verbose functions replacement. Minification is performed on the server side and only when the source file is changed.
🌐
minify-js.com
minify-js.com
Minify JS Online. JavaScript Minification tool that works in browser.
Why is Minification used?
Minification allows to reduce JavaScript file size that has a positive impact on load times and bandwidth usage. As a result, site speed and accessibility is higher compared to sites that don't use minification. Other words, minification tangibly improves user experience.
🌐
minify-js.com
minify-js.com
Minify JS Online. JavaScript Minification tool that works in browser.
🌐
Code Beautify
codebeautify.org › minify-js
Minify JS is JavaScript Minifier online
Map to Array in Javascript · JS data Try it. var carInsuranceCompany = { name: "Geico", market_capital: "$34.9 billion", }; var carInsuranceCompanyObj = JSON.stringify(obj); document.getElementById("insurance").innerHTML = carInsuranceCompanyObj; For Advanced Users · Load External URL in Browser URL like this https://codebeautify.org/ minify-js?url=external-url ·
🌐
Minify JS
minify-js.com
Minify JS Online. JavaScript Minification tool that works in browser. | Minify JS Online
Minify-JS.com is an online tool that allows you to reduce the size of JavaScript code up to 80%. The minify js tool uses the Terser utility that is compatible with the ES6+ standard. Minify-JS.code also includes helpful resources, best practices, configuration examples, and usage guides related to the JavaScript minification process.
🌐
EDUCBA
educba.com › home › software development › software development tutorials › javascript tutorial › javascript minify
JavaScript Minify | How does minify work in JavaScript? | Examples
August 13, 2024 - JavaScript modify works for removing white spaces, line breaks, block delimiters, comments etc. to reduce the size of the application file. ... Explanation: As you can see in the above after minifying the code all empty spaces and blank space are removed. All the below examples I have used https://www.minifier.org/ online compiler.
Address   Unit no. 202, Jay Antariksh Bldg, Makwana Road, Marol, Andheri (East),, 400059, Mumbai
Top answer
1 of 9
53

DIY Minification

No minifier can compress bad code properly.

In this example, I just want to show how much a minifier does.

What you should do before you minify

And regarding jQuery... I don't use jQuery. jQuery is for old browsers; it was made for compatibility reasons. Check Can I use; almost everything works in every browser (also Internet Explorer 10 is standardized now). I think now it's just here to slow down your web application... If you like the $(), you should create your own simple function. And why bother to compress your code if your clients need to download the 100 KB jQuery script every time? How big is your uncompressed code? 5-6 KB...? Not to talk about the tons of plugins you add to to make it easier.

Original Code

When you write a function you have an idea, start to write stuff and sometimes you end up with something like the following code.The code works.Now most people stop thinking and add this to a minifier and publish it.

function myFunction(myNumber){
    var myArray = new Array(myNumber);
    var myObject = new Object();
    var myArray2 = new Array();
    for(var myCounter = 0; myCounter < myArray.length; myCounter++){
        myArray2.push(myCounter);
        var myString = myCounter.toString()
        myObject[myString] = (myCounter + 1).toString();
    }
    var myContainer = new Array();
    myContainer[0] = myArray2;
    myContainer[1] = myObject;
    return myContainer;
}

Here is the minified code (I added the new lines):

Minified using (http://javascript-minifier.com/)

function myFunction(r){
 for(var n=new Array(r),t=new Object,e=new Array,a=0;a<n.length;a++){
  e.push(a);
  var o=a.toString();
  t[o]=(a+1).toString()
 }
 var i=new Array;
 return i[0]=e,i[1]=t,i
}

But are all those variables, ifs, loops, and definitions necessary?

Most of the time, NO!

  1. Remove unnecessary if,loop,var
  2. Keep a copy of your original code
  3. Use the minifier

OPTIONAL (increases the performance & shorter code)

  1. use shorthand operators
  2. use bitwise operators (don't use Math)
  3. use a,b,c... for your temp vars
  4. use the old syntax (while,for... not forEach)
  5. use the function arguments as placeholder (in some cases)
  6. remove unneccessary "{}","()",";",spaces,newlines
  7. Use the minifier

Now if a minifier can compress the code your doing it wrong.

No minifier can compress properly a bad code.

DIY

function myFunction(a,b,c){
 for(b=[],c={};a--;)b[a]=a,c[a]=a+1+'';
 return[b,c]
}

It does exactly the same thing as the codes above.

Performance

http://jsperf.com/diyminify

You always need to think what you need:

Before you say "No one would write code like the one below" go and check the first 10 questions in here ...

Here are some common examples I see every ten minutes.

Want a reusable condition

if(condition=='true'){
 var isTrue=true;
}else{
 var isTrue=false;
}
//same as
var isTrue=!!condition

Alert yes only if it exists

if(condition==true){
 var isTrue=true;
}else{
 var isTrue=false;
}
if(isTrue){
 alert('yes');
}
// The same as
!condition||alert('yes')
// If the condition is not true alert yes

Alert yes or no

if(condition==true){
 var isTrue=true;
}else{
 var isTrue=false;
}
if(isTrue){
 alert('yes');
}else{
 alert('no');
}
// The same as
alert(condition?'yes':'no')
// If the condition is true alert yes else no

Convert a number to a string or vice versa:

var a=10;
var b=a.toString();
var c=parseFloat(b)
// The same as
var a=10,b,c;
b=a+'';
c=b*1

// Shorter
var a=10;
a+='';// String
a*=1;// Number

Round a number

var a=10.3899845
var b=Math.round(a);
// The same as
var b=(a+.5)|0; // Numbers up to 10 decimal digits (32bit)

Floor a number

var a=10.3899845
var b=Math.floor(a);
// The same as
var b=a|0;//numbers up to 10 decimal digits (32bit)

switch case

switch(n)
{
case 1:
  alert('1');
  break;
case 2:
  alert('2');
  break;
default:
  alert('3');
}

// The same as
var a=[1,2];
alert(a[n-1]||3);

// The same as
var a={'1':1,'2':2};
alert(a[n]||3);

// Shorter
alert([1,2][n-1]||3);
// Or
alert([1,2][--n]||3);

try catch

if(a&&a[b]&&a[b][c]&&a[b][c][d]&&a[b][c][d][e]){
 console.log(a[b][c][d][e]);
}

// This is probably the only time you should use try catch
var x;
try{x=a.b.c.d.e}catch(e){}
!x||conole.log(x);

More if

if(a==1||a==3||a==5||a==8||a==9){
 console.log('yes')
}else{
 console.log('no');
}

console.log([1,3,5,8,9].indexOf(a)!=-1?'yes':'no');

But indexOf is slow. Read this: How do I check if an array includes a value in JavaScript?

Numbers

1000000000000
// The same as
1e12

var oneDayInMS=1000*60*60*24;
// The same as
var oneDayInMS=864e5;

var a=10;
a=1+a;
a=a*2;
// The same as
a=++a*2;

Some nice articles/sites I found about bitwise/shorthand:

http://mudcu.be/journal/2011/11/bitwise-gems-and-other-optimizations/

http://www.140byt.es/

http://www.jquery4u.com/javascript/shorthand-javascript-techniques/

There are also many jsperf sites showing the performance of shorthand & bitwise if you search with your favorite search engine.

I could go one for hours.. but I think it's enough for now.

If you have some questions, just ask.

And remember:

No minifier can compress properly bad code.

2 of 9
37

You could use one of the many available JavaScript minifiers.

  • YUI Compressor
  • Google closure compiler
  • Dean Edwards packer
  • JSMin
Find elsewhere
🌐
Toptal
toptal.com › developers › javascript-minifier
JavaScript Minifier & Compressor | Toptal®
JavaScript Minifier · ClearMinify · Copy to Clipboard · The API has changed, to see more please click here · To minify/compress your JavaScript, perform a POST request to · API https://www.toptal.com/developers/javascript-minifier/api/raw · with the input parameter set to the JavaScript you want to minify.See the documentation ·
🌐
Minifier
minifier.org
Minify JS / CSS - JavaScript and CSS Minifier / Compressor
You can paste .js or .css file, or just plain javascript or CSS code. This JS and CSS minifier removes whitespace, strips comments, combines files, and optimizes/shortens a few common programming patterns.
🌐
GitHub
gist.github.com › yairEO › 9d8e18a330aab275bc86b56075fc234e
HTML string minify / compress to single-line · GitHub
HTML string minify / compress to single-line · Raw · minifyHTML.js · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
🌐
Jscompress
jscompress.com
JSCompress - The JavaScript Compression Tool
We use UglifyJS 3 and babel-minify for all JavaScript minification and compression.
🌐
GitHub
gist.github.com › getify › 5935939
Example of how to use JSON.minify() to pre-process your JSON strings and remove comments (and whitespace) before parsing. · GitHub
Example of how to use JSON.minify() to pre-process your JSON strings and remove comments (and whitespace) before parsing. - data.json
🌐
MetaCPAN
metacpan.org › pod › JavaScript::Minifier
JavaScript::Minifier - Perl extension for minifying JavaScript code - metacpan.org
The primary requirement developing this module is to not break working code: if working JavaScript is in input then working JavaScript is output. It is ok if the input has missing semi-colons, snips like '++ +' or '12 .toString()', for example. Internet Explorer conditional comments are copied to the output but the code inside these comments will not be minified.
🌐
npm
npmjs.com › package › string-minify
string-minify - npm
This helper removes all extra whitespaces, tabs, newlines and trims the string.. Latest version: 1.0.1, last published: 6 years ago. Start using string-minify in your project by running `npm i string-minify`. There are 3 other projects in the ...
      » npm install string-minify
    
Published   Aug 19, 2019
Version   1.0.1
Author   Sergey Lysenko
🌐
Kangax
kangax.github.io › html-minifier
HTML minifier
Process scripts Comma-delimited string corresponding to types of script elements to process through minifier (e.g. text/ng-template, text/x-handlebars-template) Quote character Type of quote to use for attribute values (' or ") Remove attribute quotes Remove quotes around attributes when possible ... Remove redundant attributes Remove attributes when value matches default. Remove script type attributes Remove type="text/javascript...
🌐
GitHub
github.com › kangax › html-minifier
GitHub - kangax/html-minifier: Javascript-based HTML compressor/minifier (with Node.js support) · GitHub
Array of strings corresponding to types of script elements to process through minifier (e.g. text/ng-template, text/x-handlebars-template, etc.) ... Remove attributes when value matches default. ... Remove type="text/javascript" from script tags.
Starred by 5.1K users
Forked by 583 users
Languages   JavaScript 94.9% | HTML 4.6% | CSS 0.5%
🌐
DEV Community
dev.to › stackfindover › how-to-create-code-compressor-in-javascript-html-minifier-32i
How to create code compressor in JavaScript | HTML Minifier - DEV Community
June 29, 2021 - <script> var $tag = function(tag) { return document.getElementsByTagName(tag); } function minify_html(type, input, output) { output.value = input.value .replace(/\<\!--\s*?[^\s?\[][\s\S]*?--\>/g,'') .replace(/\>\s*\</g,'><'); } document.getElementById("htmlMinify").addEventListener("click", function(){ minify_html( this.innerHTML, $tag('textarea')[0], $tag('textarea')[1] ); }, false); </script> ... Hi, I’m Rahul Jangir — a tech geek, design enthusiast, and online expert. I’m a technology graduate with a deep addiction to front-end development. I love blending AI, design, and development to build ... I do like your answer I think it has a great specific use case, but I am confused by the rigidity of this approach. Example if someone minifies a chunk of html which has no doctype or head or body.
🌐
freeCodeCamp
freecodecamp.org › news › javascript-minify-minifying-js-with-a-minifier-or-jsmin
JavaScript Minify – Minifying JS with a Minifier or jsmin
November 2, 2022 - I'll share two minifying tools you can use. This tool removes whitespace, strips comments, combines files, and optimizes a few common programming patterns. You install the tool on your device and configure it in your code with the JavaScript path that you want you to minify for production.
🌐
Code Beautify
codebeautify.org › text-minifier
Minify Text - CodeBeautify
Binary to String Converter · Case Converter · Delimited Text Extractor · Remove Accents · Remove Duplicate Lines · Remove Empty Lines · Remove Extra Spaces · Remove Line Breaks · Remove Lines Containing · Sort Text Lines · CSS Validator · JAVASCRIPT Validator ·