Uglified Unicode on Rails

TL;DR - IE doesn’t like minified unicode. To fix this, create a custom passthrough minifier to disable minification of unicode when using uglify in the rails asset pipeline.

I’m pretty new to rails, so please let me know if I’m off the mark here.

Asset Pipeline

Rails has an interesting component called the asset pipeline that, among other things, can combine all of your js files into one file, and all of your CSS files into another, then it can strip out whitespace and rewrite your code to make it smaller, by doing things such as replacing long variable names with short ones. This is called combining and minifying. Combining and minifying are important because they can help a web page to load faster. A web page can load noticably faster if it has a single 150kb file to load from the server rather than 25 files that are 10kb each.

Without question, we wanted to minify and combine our code using the asset pipeline. For more information on setting up minification, see the asset pipeline documentation.

IE and Unicode Problems

However, we had strange results with the minification. When our code was _not _minified, it worked great in both IE and Chrome. After being minified by the asset pipeline, however, it worked great in Chrome but some parts of our app mysteriously failed in IE.

I took a look at our minified code and saw this:

That looked a little funny. I went and found the corresponding source javascript and saw some lines like this:

DFA4_transitionS: [
“\u0001\u0017\u0002\uffff\u0001\u0017\u0012\uffff\u0001\u0011”,

That’s unicode. Hmm… It appears IE doesn’t like minified unicode.

Configuring Uglifier

I did some digging and discovered that the Asset Pipeline was using uglifier to do to the minification. Looking at the Uglifier documentation, I saw that there was a configuration option that looked promising:

# Encode non-ASCII characters as Unicode code points
:ascii_only => false,

However, try as I might, I couldn’t figure out how to set this configuration option on uglifier in the asset pipeline.

Custom Minifier

So instead, I created my own custom minifier. First, I created lib/custom_uglify.rb. All it does is define a compress method that calls compile on the Uglifier class, passing in the option to use ascii_only.

require ‘uglifier’
class CustomUglify
def compress(string)
Uglifier.new(:ascii_only => true).compile(string)
end
end

Then, in production.rb I added this to the top of the file:

require “custom_uglify”

And then I told it to use my custom uglifier:

config.assets.js_compressor = CustomUglify.new

Result

This allowed me to pass the ascii_only setting to uglifier, which in turn provided minified javascript that IE was happy with. Problem solved!