How to bundle specific CSS according to browser version?

我的未来我决定 提交于 2019-12-10 12:22:05

问题


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?


回答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.




回答2:


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



来源:https://stackoverflow.com/questions/13039792/how-to-bundle-specific-css-according-to-browser-version

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!