jQuery 1.x && 2.x + MVC script bundling

large_jquery_logoIn 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…
 

   1:  //bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
   2:  //            "~/Scripts/jquery-{version}.js"));
   3:   
   4:  // Conditionally use the newer jQuery 2* in modern browers, 
   5:  //   layout page contains conditional inclusion logic
   6:  bundles.Add(new ScriptBundle("~/bundles/jquery1x").Include("~/Scripts/jquery-1*"));
   7:  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…
 

   1:  <!-- Conditionally include jQuery version based on IE version -->
   2:  <!--[if lt IE 9]>
   3:  @Scripts.Render("~/bundles/jquery1x")    <![endif]-->
   4:  <!--[if gte IE 9]><!-->
   5:  @Scripts.Render("~/bundles/jquery")    <!--<![endif]-->

If you run your page and look at “page source” – you see…
 

   1:  <!-- Conditionally include jQuery version based on IE version -->
   2:  <!--[if lt IE 9]>
   3:  <script src="/Scripts/jquery-1.8.2.js"></script>
   4:  <![endif]-->
   5:  <!--[if gte IE 9]><!-->
   6:  <script src="/Scripts/jquery-2.0.3.js"></script>
   7:  <!--<![endif]-->

That’s it!  Now you get the best version of jQuery for the browser… sweet…

Leave a Reply