Thursday, October 4, 2007

Combine multiple stylesheets at runtime

 

Mad Kristensen (founder of BlogEngine.Net) has written a great article titled Combine multiple stylesheets at runtime. In the article he outlines the process of combining multiple stylesheet references from the head tag on a page into one http request instead of the multiple ones and he also throws in some performance gains via whitespace removal and browser caching.

The ability to combine stylesheet requests is something that I have looked at in the past for one of our applications and never quite found the right solution. However, this solution looks very promising for the following reasons:

  • Provides the ability to reference a stylesheet inclusion in the normal HTML markup (note that your head tag must have the runat='server' attribute applied).
  • Efficiently leverages browser caching without the need for modifying content expiration via Http Headers on files/directories within IIS.
  • Satisfies Best Practice #1 Make Fewer Http Requests of the Yahoo Developer Network Best Practices for Speeding Up Your Web Site. (Note you can grade the performance of your web site using YSlow for FireFox.)
  • Provides a file dependency for all of the scripts that make up the caching of the generated combined script so you can update those files dynamically as needed.

Granted there is the initial IO overhead the first time of the combined requests needs to be generated, but I think that is a small price to pay for longer term performance increases in your web application.

No comments: