Extending System.Web.Optimization

The ASP.NET framework is packed with loads of great features and with each release it seems to get better and better. One of my favourite features is the bundling and minification classes that optimize JavaScript and CSS files in a website to reduce file size and improve page performance.

ASP.NET logo

By bundling and minifying your scripts and styles, you can significantly improve your page load times. While the built in classes in the System.Web.Optimization namespace are easy to use, I find that they aren't very flexible. HTML5 has a few additional attributes that allow you to do many more things with your page functionality, but currently you can't use these attributes with the built in System.Web.Optimization classes. I wanted to be able to add extra HTML attributes to the tags while still using the built in functionality that the framework provides. I created the class below that extends the current ASP.NET optimization functionality, yet still allows you some flexibility.

Simply drop the above code into your project and it's ready to go. Say for example you wanted to include the async attribute on your JavaScript tag, using the code above, you simply call it like so:

@Bundler.RenderScripts("~/Js/Spaces", new { async = "true" })

Which will produce the following script tag:

<script src="/Js/Spaces?v=IJe2dZiudhgHX-5go2gdHoyVzF1zdP6jlBYm2g_OYU41" async="true" />

The async attribute is a great HTML5 feature that can improve your page performance by stopping scripts from blocking your page loading. I have previously blogged about the async attribute and the defer attribute and for more information about this, please check out this link.

Using the code above, if you wanted to add extra attributes to your style tag(s), you would call it like so:

@Bundler.RenderStyles("~/Css/Spaces", new {media = "print"})

The code above will produce the following style tag:

<link href="/Css/Spaces?v=OVeDyrP68xENlN98" rel="stylesheet" media="print"/>

Hopefully this class will come in handy when you next need to add HTML attributes to your tags while still leveraging the power of the System.Web.Optimization classes.


Drew - 3/27/2014
Could this be modified to accept raw CSS or Javascript? An example would be if I wanted to pull raw CSS from a database an inject it into the bundle.

Scott - 12/3/2015
Almost two years later... but this should be able to check BundleTable.EnableOptimizations instead of performing the preprocessor directive checks for the DEBUG symbol.

Add your comment

300 Characters left

Please fill this in to confirm that you are human