Create a Script bundle from multiple locations

Иван Грозный picture Иван Грозный · Nov 27, 2013 · Viewed 17.4k times · Source

Let's assume our app is offline, i.e. we can't use 3rd party CDNs thus we're creating our own. I'd like to host all of the vendor scripts in a separate (Parent) web app and then include them in the bundles in several other MVC Apps.

e.g.

  • http://localhost/parentWeb/Scripts/jquery.js
  • http://localhost/parentWeb/Scripts/jquery-ui.js
  • http://localhost/parentWeb/Scripts/globalize.js

I'd like to include in the ASP.NET MVC App Website located in: http://localhost/parentWeb/childWeb

i.e. do something like this:

bundles.UseCdn = true;
bundles.Add(
    new ScriptBundle(
        "~/bundles/VendorScripts",
        "http://localhost/parentWeb/Scripts/jquery.js",
        "http://localhost/parentWeb/Scripts/jquery-ui.js",
        "http://localhost/parentWeb/Scripts/globalize.js"));

...which of course isn't currently possible. Is there a good workaround?

Answer

Chris Pratt picture Chris Pratt · Nov 27, 2013

You can't bundle external resources. If you think about it, it makes sense why you can't. It would require the bundler to actually download the resource and save it to the filesystem before it could work with it, and of course do it all asynchronously with some sort of fallback if the external resource couldn't be reached. And, then, it would have to do this on every page load because it can't check for lastmod (and therefore, know whether it actually needs to rebundle or not) without fetching the resource first.

If you use a CDN resource, the bundler merely prints the URL directly to the page; it doesn't make any modifications. Even then, it only lets you create a "bundle" of just that one URL, because 1) it wouldn't make sense to bundle multiple CDN resources since that would defeat the purpose of a CDN and 2) the bundle only exists in this scenario to provide a fallback if the CDN resource is unavailable. Otherwise, you would be served just as well by just hardcoding it to the page and not worrying about setting up a bundle at all.