⬆️ ⬇️

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.

For ASP.NET sites there is an excellent library SquishIt - it allows you to combine both css files into one, and JavaScript files. I will not describe in detail the advantages of combining since they were already mentioned in the article above and others, the main thing is a decrease in the number of requests to the server.



This library is available as a Nuget package .

You have 2 options available:



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”.



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


')

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



 @{ SquishIt.Css.Add("~/Content/Site.css"); SquishIt.Css.Add("~/Content/themes/base/jquery-ui.css"); SquishIt.Css.Add("~/Content/reset.css"); SquishIt.JavaScript.Add("~/Scripts/jquery-1.4.4.js"); SquishIt.JavaScript.Add("~/Scripts/MicrosoftAjax.debug.js"); } <!DOCTYPE html> <html> <head> <title>@ViewBag.Title</title> @SquishIt.Css.Render("~/Content/combined_#.css") @SquishIt.JavaScript.Render("~/Scripts/combined_#.js") </head> 




And also change debug to false in “Web.config”



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




Is done. As a result, we get the following:



 <head> <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> </head> 




It should be noted that "_ #" means that the 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 allows you to avoid problems with the cache, if at least one of the files was changed.



If you use WebForms to, the code will be as follows:

 <%@ Import Namespace="SquishIt.Framework" %> <%= Bundle.JavaScript() .Add("~/Scripts/jquery-1.4.2.js") .Add("~/Scripts/jquery-ui-1.8.1.js") .Render("~/Scripts/combined_#.js") %> 




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



GitHub link

Source: https://habr.com/ru/post/130303/



All Articles