Skip to content Skip to sidebar Skip to footer

Prevent Closure Compiler From Duplicating String

I'm using Google's Closure compiler to shrink my JS. There are several places in my code where I have a repeated string, e.g. (function($){ $('.bat').append('

the red car

Solution 1:

This behavior is documented here:

http://code.google.com/p/closure-compiler/wiki/FAQ#Closure_Compiler_inlined_all_my_strings,_which_made_my_code_size

However, one approach I've used to avoid when I have add a very large string that is worth deduplicating is to wrap the value in a function:

const getCssStyleSheetText = () => "...";

and to call that function when I need the text. The compiler uses a different heuristic when inlining functions and will only inline a function if it estimates that it will reduce code size. Therefore a function returning a string will be inlined if it is called once but left alone if it is called many times.

Ideally, the compiler would be a little more nuanced about inlining strings but in general the approach it takes works out well enough.

Post a Comment for "Prevent Closure Compiler From Duplicating String"