Question

Is there any way I can do this?

Some of the benefits of bundling are:

  • Minimization
  • Gzip compression
  • The request has a token parameter for handling files versiones (cache).

In my site I use a lot of bundles, but in some pages I only have 1 script and I don't think I should create a bundle only for 1 script. Is there any way I can use this three benefits with Url.Content method.

My utopic solution would be to set up something (maybe in the web.config) and whenever Url.Content is called it adds this functionality. Using it in either of this ways:

<script type="text/javascript" src="@Url.Content("~/Scripts/...")"></script>
<script type="text/javascript" src="~/Scripts/..."></script>

(The second one is because I'm using Razor 2)

If that is not possible I can make an extension method to UrlHelper to add this functionality.

Thanks!

Était-ce utile?

La solution

There's nothing really wrong with creating a bundle with one file to get the benefits of minification and versioning. You would have to use the Scripts.Render helper as well, there's no support for this in the UrlHelper currently, but as you mentioned already you could write an extension method to call into the Scripts helper.

Update (by OP)

Here are my extension method for anyone who want to use it:

public static IHtmlString DynamicScriptsBundle(this HtmlHelper htmlHelper, string nombre, params string[] urls)
{
    string path = string.Format("~/{0}", nombre);
    if (BundleTable.Bundles.GetBundleFor(path) == null)
        BundleTable.Bundles.Add(new ScriptBundle(path).Include(urls));
    return Scripts.Render(path);
}

public static IHtmlString DynamicStylesBundle(this HtmlHelper htmlHelper, string nombre, params string[] urls)
{
    string path = string.Format("~/{0}", nombre);
    if (BundleTable.Bundles.GetBundleFor(path) == null)
        BundleTable.Bundles.Add(new StyleBundle(path).Include(urls));
    return Styles.Render(path);
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top