.NET Tips and Tricks

Blog archive

Leveraging and Testing Script Bundles with Content Delivery Networks

You can significantly reduce the time your users wait to see your ASP.NET pages by bundling your site's JavaScript files into a single zip file. You're not limited to downloading just your script files, however: There's nothing stopping you from including files from the Content Delivery Network of your choice. All you have to do is pass the URL to the CDN as the second parameter when you create a ScriptBundle, like this:

bundles.UseCdn = true;
bundles.Add(new ScriptBundle("~/bundles/jquery", 
                             "https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.1.min.js")
.Include( ... local script files ... ));

Microsoft recommends you provide a fallback when you use a CDN, in case the CDN isn't available. Microsoft suggests a script tag like that shown below to follow the script elements that fetch your script files. This code checks to see if the objects in the CDN file have been downloaded (jQuery, in my example) then goes and gets a local copy of the file if they're not:

<script type="text/javascript">
  if (typeof jQuery == 'undefined') {
    var e = document.createElement('script');
    e.src = '@Url.Content("~/Scripts/jquery-1.7.1.js")';
    e.type = 'text/javascript';
    document.getElementsByTagName("head")[0].appendChild(e);
  }
</script>

Personally, I think it's more likely that your scripts won't be available.

You'll want to test this, of course, but ASP.NET will steadfastly refuse to bundle your scripts when running in debug mode. If you want, you can add this line of code to your BundleConfig file in your project's App_Start folder to enable bundling even in debug mode:

BundleTable.EnableOptimization = true;

Posted by Peter Vogel on 10/25/2018 at 8:57 AM


Featured

  • Swirl

    Blazor WebAssembly Not Ready for .NET Core 3.0 Prime Time

    The much-anticipated .NET Core 3.0 milestone release is shipping in five days, Sept. 23, but it won't include a stable Blazor WebAssembly.

  • Visual Studio 2019 16.3 Preview Adds .NET Core Database Profiling

    Microsoft shipped Visual Studio 2019 16.3 Preview 4, adding database profiling for projects based on .NET Core, which is coming out in a big v3.0 milestone release next week.

  • Release Candidates Out for Entity Framework Core 3.0 and Entity Framework 6.3

    After shipping Preview 9 versions of Entity Framework Core 3.0 and Entity Framework 6.3 a couple weeks ago and saying, "These are the last planned previews before we release the final versions later this month," Microsoft this week belied that with new Release Candidate builds.

.NET Insight

Sign up for our newsletter.

Terms and Privacy Policy consent

I agree to this site's Privacy Policy.

Upcoming Events