Breaking the minified version of your CSS every 32k chars, will make the CSS parser’s life easier.

Last week we had an interesting problem related to CSS parsing on Android 4.x. The application was working perfectly on Android 5+ and iOS devices. When We tried to test it on Android 4.x We saw the problem. For some magical reason all the CSS rules wasn’t being applied to the interface. I don’t know how familiar you are with development of websites or hybrid application for Android, but I can tell you that debugging HTML, CSS or Javascript on Android 4.x Stock browser is a pain in the neck.

Since we are building a large application using Angular JS with many custom directives, the first attempt was to remove all code. “… I don’t know … maybe some code is breaking the entire application …” (me, at desperation times). We are using Websocket to connect to our back-end, Weinre also uses Websocket to allow us debug the application, so, the choice to remove all code to check the CSS was reasonable.

After a frustrated tentative debugging the CSS, that wasn’t being displayed on Weinre client page, Leo suggested me to load a small temporary CSS file. It worked! So, something was wrong with our CSS, right? Since our CSS was minified, we tried to load it non-minified. And it worked again! Somehow, the process to minify the CSS file was the problem.

At least now We could simulate the error, knowing when it happens. Ok, the size of the CSS minified was 160kb, 160.000 characters in one single line. What if we try to break it on several lines without losing the minification? We did it, and it worked perfectly. Breaking the CSS on several lines, after the minification, fixed our problem. But the question now is: What is the maximum line size, safe enough to keep the file with the minimum amount of lines?

Few days after, Leo came back with a link from a question at Promasters Stack Exchange, with a similar problem. The same link pointed to two other links, one at Clojure Compiler and the other at UglifyJS (JQuery tool for minification). Close Compiler breaks the minified code every 500 characters due to some proxies that corrupts some JS files that contains large lines of code. UglifyJS, break the code every 32k chars because they noticed some struggling from Chrome and Firefox to parser lines bigger than 670k.

Our application is using Compass CSS,  although it provides different types of output, it doesn’t provide a option to define the maximum line length for production output. The easy solution was to break the line after each CSS rule, basically replacing “}” for “}\n”. This was just a small fix to allow us to deploy the application in time. Our goal now is to find, or build, a tool to do it for us in a smarter way to optimize the minification without exceed the 32k chars per line.