Search code examples
asp.netjavascriptcsscachingcompression

CSS compression & combining / js minification - Better to do at runtime or at build time?


I have to come up with a solution to compress, version (for caching purposes) and potentially combine our JS and CSS files and I've seen two dominant approaches so far:

1) At build time: As an MSBuild task or similar. 2) Dynamically at run time: As a custom HTTPHandler (we are ASP.NET btw) for .js and .css files, with something like this ending up in your pages:

<link rel="stylesheet" type="text/css" href="~/StyleSheetHandler.ashx?stylesheets=~stylesheets/master.css" /> 

Can anyone provide information of pro's and con's of each? Personally, I can't see the point of doing it dynamically and wasting CPU cycles at the time of each request (I guess you'd only do with the work first time and then cache, but still) but I get the feeling I might be missing something?

Thanks! Mark.


Solution

  • I think a good approach is to use different strategies for different environments:

    • no compression for development (for developing & debugging)
    • runtime compression for test environment (flexible, not performance-critical)
    • buildtime compression for staging and production (tested, performance-critical)

    I have some experience using the YUI compressor for both Javascript and CSS and have learned (the hard way) that testing minified JS and CSS is indeed very important.

    Creating static minified JS and CSS files as part of your build for production has the following benefits:

    • they are tested
    • static files, can be served without ASP.NET overhead
    • can be browser cached
    • should be webserver-gzipped