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