How to bundle specific CSS according to browser ve

2019-06-14 04:22发布

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?

2条回答
萌系小妹纸
2楼-- · 2019-06-14 04:42

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.

查看更多
淡お忘
3楼-- · 2019-06-14 04:49

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

查看更多
登录 后发表回答