jQuery 1.x && 2.x + MVC script bundling
In my blog “NuGet – Limiting updates for jQuery and Bootstrap” – we looked at continuing to utilize NuGet to keep us up to date on the latest jQuery 1.x version ( even though 2.x is out ). Reason being…
In my blog “NuGet – Limiting updates for jQuery and Bootstrap” – we looked at continuing to utilize NuGet to keep us up to date on the latest jQuery 1.x version ( even though 2.x is out ). Reason being that we needed to stick with 1.x because we are still supporting IE 7/8. 🙁
So… jQuery 1.x and 2.x have feature parity – but you want to use jQuery 2.x when you can, simply because it’s a smaller download as they were able to take out a lot of IE7/8 “fixes”. Note, jQuery’s post on conditionally include one or the other based on the version of the browser.
But we also like to use the cool MVC bundling and minification feature – can we have the best of all worlds? Oh ya… 🙂
So if you started with the default MVC project, in your /App_Start/BundleConfig.cs – you will find the “~/bundles/jquery” bundle – comment out line 1 + 2, and add the following lines…
//bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
// "~/Scripts/jquery-{version}.js"));
// Conditionally use the newer jQuery 2* in modern browers,
// layout page contains conditional inclusion logic
bundles.Add(new ScriptBundle("~/bundles/jquery1x").Include("~/Scripts/jquery-1*"));
bundles.Add(new ScriptBundle("~/bundles/jquery").Include("~/Scripts/jquery-2*"));
Next, open up your /Views/Shared/_Layout.cshtml – and at the bottom of the page, change it to look as follows…
<!-- Conditionally include jQuery version based on IE version -->
<!--[if lt IE 9]>
@Scripts.Render("~/bundles/jquery1x") <![endif]-->
<!--[if gte IE 9]><!-->
@Scripts.Render("~/bundles/jquery") <!--<![endif]-->
If you run your page and look at “page source” – you see…
<!-- Conditionally include jQuery version based on IE version -->
<!--[if lt IE 9]>
<script src="/Scripts/jquery-1.8.2.js"></script>
<![endif]-->
<!--[if gte IE 9]><!-->
<script src="/Scripts/jquery-2.0.3.js"></script>
<!--<![endif]-->
That’s it! Now you get the best version of jQuery for the browser… sweet…