Combining and compressing CSS and JS files in ASP.NET web applications

Published on October 12, 2011

Combining and compressing CSS and JS files in ASP.NET web applications

    Good day!

    I have long thought to write a post on this topic, but decided only after this topic about combining JavaScript files.
    There is an excellent SquishIt library for ASP.NET sites - it allows you to combine both css files into one and JavaScript files. I will not describe in detail the advantages of the union, as they were already mentioned in the article above and others, the main thing is to reduce the number of server requests.

    This library is available as a Nuget package .
    You have 2 options:

    If you will be using ASP.NET MVC, you need to make changes to the “Views / Web.config” file,
    in the “system.web.webPages.razor” section, change the “pageBaseType” attribute in the “pages” section to “SquishIt.Contrib.Mvc .SquishItBasePage. "

        <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <pages pageBaseType="SquishIt.Contrib.Mvc.SquishItBasePage">
    <add namespace="System.Web.Mvc" />
            <add namespace="System.Web.Mvc.Ajax" />
            <add namespace="System.Web.Mvc.Html" />
            <add namespace="System.Web.Routing" />

    And now you can actually combine elephants with flies css and js files.

    <!DOCTYPE html>

    And also change debug to false in "Web.config"

     <compilation debug="false" targetFramework="4.0">

    Done. As a result, we get the following:

        <title>Home Page</title>
          <link rel="stylesheet" type="text/css" href="/Content/combined.css?r=531A7BFA4E917B223909817F07467EDB" />
          <script type="text/javascript" src="/Scripts/combined.js?r=6DB45040EF233910B7E1F986316FF2FE"></script>

    It is worth noting that "_ #" means that a hash of the content will be added to the file name, if it is not specified, it will be added as a request parameter. This avoids cache problems if at least one of the files has been changed.

    If you use WebForms to code will be as follows:
    <%@ Import Namespace="SquishIt.Framework" %>
    <%= Bundle.JavaScript()

    As a result, within 10 minutes we can significantly speed up the loading of a web site using the SquishIt library.

    GitHub Link