0

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?

Hao Kung
  • 28,040
  • 6
  • 84
  • 93
Ray Cheng
  • 12,230
  • 14
  • 74
  • 137
  • 1
    Are you creating these bundles in the Global.asax? That is what would cause this error. I don't think the Bundles support Request-based bundles, but instead a global bundle. – Tejs Oct 23 '12 at 21:50
  • @Tejs, it's being called at `Application_Start`. – Ray Cheng Oct 23 '12 at 21:56
  • 2
    Yeah, I don't believe the framework provides for variant based bundles; it's a global all or nothing. If you want to make various bundles per browser, you need to make those all separate bundles and then write the reference to the bundle you want in each view. – Tejs Oct 23 '12 at 21:59

2 Answers2

3

you can add something like :

<script type="text/javascript">
    var domLib = '@System.Web.Optimization.BundleTable.Bundles.ResolveBundleUrl("~/Zepto")';
    if (navigator.userAgent.indexOf('MSIE ') > -1) {
        domLib = '@System.Web.Optimization.BundleTable.Bundles.ResolveBundleUrl("~/Jquery")';
    }
    document.write('<script src="' + domLib + '"><\/script>');
</script>

In this example I use the library Zepto, and Jquery if it's Internet Explorer. It works fine for me. Pierre

pierrehenri56
  • 436
  • 4
  • 6
1

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.

Hao Kung
  • 28,040
  • 6
  • 84
  • 93