Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Solution to minify object properties?

In my JavaScript application, I use several objects for internal purposes only (the users don't need to access them). for example:

var images={
    blank:"blank.gif",
    plus:"plus.gif",
    minus:"minus.gif"
}

When I use a minifier like Uglify.js, the property names (blank, plus, minus) are kept as is. Is there a way to minify them?

What I have considered so far:

  • use Google Closure minifier in advanced mode, but this crushes my code
  • replace object properties with variables (e.g. var imagesBlank="blank.gif") but it makes the code less readable

Is there a better way?

like image 867
Christophe Avatar asked Feb 21 '12 17:02

Christophe


People also ask

How do you minify?

Go to minifycode.com and click the CSS minifier tab. Then paste the CSS code into the input box and click the Minify CSS button. After the new minified code is generated, copy the code. Then go back to the css file of your website and replace the code with the new minified version.

What is the difference between minify and uglify?

Minification is just removing unnecesary whitespace and redundant / optional tokens like curlys and semicolons, and can be reversed by using a linter. Uglification is the act of transforming the code into an "unreadable" form, that is, renaming variables/functions to hide the original intent...

What can be Minified?

Minification is the process of minimizing code and markup in your web pages and script files. It's one of the main methods used to reduce load times and bandwidth usage on websites. Minification dramatically improves site speed and accessibility, directly translating into a better user experience.

How does Minification reduce file size?

How Minification Works. Minification works by analyzing and rewriting the text-based parts of a website to reduce its overall file size. Minification extends to scripts, style sheets, and other components that the web browser uses to render the site. Minification is performed on the web server before a response is sent ...


1 Answers

Using an object allows the use of variables as properties. Wrapping it in a closure makes those variables worthy of minifying.

//Wrap in closure
(function() {

    //Property Variables
    var blank = 0;
    var plus  = 1;
    var minus = 2;

    //Define Object
    var image = [];
    image[blank] = "blank.gif";
    image[plus]  = "plus.gif";
    image[minus] = "minus.gif";

    //Accessors - must be within closure
    image[blank]; //blank.gif
    image[plus];  //plus.gif
    image[minus]; //minus.gif

})();

To access the values above, the constants must be used within the closure.

If using Google's Closure Compiler, using var image = []; will be more efficient in declaring the array since the property values are numbered from zero, i.e. 0, 1, 2.

Otherwise, var image = {}; works well too.

like image 145
Wasmoo Avatar answered Sep 22 '22 09:09

Wasmoo