Search code examples
c#asp.net-mvc-4asp.net-optimization

How to bundle specific CSS according to browser version?


I'm using MVC4 StyleBundle to bundle up a bunch of CSS. There is one CSS that's only needed for IE 9 or lower.

In my BundleConfig class of RegisterBundles method, I have:

if (HttpContext.Current.Request.Browser.Browser.Trim().ToUpperInvariant().Equals("IE") && HttpContext.Current.Request.Browser.MajorVersion <= 9)
    cssBundle.Include("~/Content/ie.css");

But then I got a Request is not available in this context error. Is it not possible to detect browsers during RegisterBundles method?


Solution

  • Yep Tejs is correct. Bundles are global and cannot vary based on request because they are cached on the server after being referenced for the first time. So the issue with what you are doing above, is that depending on what browser hits the request first, that will populate the cache and determine what all subsequent requests will recieve, regardless of whether they are IE9 or not.