10

I'm trying to render a JavaScript bundle using Microsoft's Web Optimization framework, like this:

@Scripts.Render("~/assets/bundle.js")

And building a small bundle, like this:

public static void RegisterBundles(BundleCollection bundles)
{
    bundles.Add(new ScriptBundle("~/assets/bundle.js")
        .Include(
            "~/scripts/jquery-2.1.0.min.js",
            "~/scripts/somescript.js"
        ));

    ...
}

But when optimizations are on, it only renders a relative URL, like this:

<script src="/assets/bundle.js?v=mGDOiNaiTrSfcNq41OoA7A_BcN8PrXuMbfl-TE84HVY1"></script>

How can I have script bundling render an absolute URL instead? I couldn't find a way to do this looking through the docs on MSDN. This is what I would ultimately like:

<script src="http://my.site.com/assets/bundle.js?v=mGDOiNaiTrSfcNq41OoA7A_BcN8PrXuMbfl-TE84HVY1"></script>

Is this in the framework, or do I have to roll a helper method with Script.Url?

MikeSmithDev
  • 15,731
  • 4
  • 58
  • 89
Brandon Linton
  • 4,373
  • 5
  • 42
  • 63
  • [This may help](http://stackoverflow.com/a/15663014/1810243). Though IDK if there may be a better way to do in newer version of bundling. What is your end-goal in doing this? – MikeSmithDev Feb 12 '14 at 15:57
  • That still resolves to a relative URL unfortunately. The relative paths generally work fine for the browser, but don't work well for UI controls (say in iOS) where you don't provide a baseURL. – Brandon Linton Feb 12 '14 at 16:28

1 Answers1

22

One easy way is with Scripts.RenderFormat:

@Scripts.RenderFormat("<script src='http://my.site.com{0}'></script>","~/assets/bundle.js")

A way to get URL from request. Couldn't seem to use multiple parameters with the RenderFormat, so that's why it looks a little ugly:

 @Scripts.RenderFormat("<script src='//" + @Request.Url.Host + "/{0}'></script>", "~/assets/bundle.js")

or better yet, centralize a function to get the correct path (using a fictional function):

@Scripts.RenderFormat("<script src='" + @Tools.GetRootURL() + "{0}'></script>", "~/assets/bundle.js")

Also, you don't need the .js on the bundle:

bundles.Add(new ScriptBundle("~/assets/bundle")
mattmanser
  • 5,719
  • 3
  • 38
  • 50
MikeSmithDev
  • 15,731
  • 4
  • 58
  • 89
  • Thanks for this; I agree this would work, although then I'd have to config drive a root URL per environment when I'd really rather it go off of the host / virtual app path. If it's truly absent from the framework, then I'd try to infer it from the request. – Brandon Linton Feb 12 '14 at 18:04
  • @BrandonLinton added way to determine URL from request. – MikeSmithDev Feb 12 '14 at 18:12