问题
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