Pergunta

Many code examples, and the default RegisterBundles method in BundleConfig.cs generated by Visual Studio 2012 for a new MVC app, include code like this to add common JavaScript files like jQuery to a bundle:

    bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                "~/Scripts/jquery-{version}.js"));

In a certain percentage of cases, the user's browser will already have those common files in its cache. So, it seems wasteful to wait for the file to be downloaded again via bundling.

Unless the browser can recognize that the bundled file (which may be concatenated with other files and minified) is already present, then it seems like this use of bundling would not speed things up at all, but rather cause unnecessary delays.

Or am I missing something here? Perhaps the probability is low that the "common" file (jQuery, etc.) is already cached?

Foi útil?

Solução

"the user's browser will already have those common files in its cache"

Not true. You are referencing your local copy, so it will only be in the cache if they have been to your site before... and if you weren't using bundling before, then no, it won't be cached. After the first download though, yes it will remain cached until you change the scripts.

If you want to reference a version that a user likely has cached, then you could use a CDN. Code below is from ASP.NET Bundling and Minification

public static void RegisterBundles(BundleCollection bundles)
{   
    bundles.UseCdn = true;   //enable CDN support
    var jqueryCdnPath = "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.1.min.js";
    bundles.Add(new ScriptBundle("~/bundles/jquery",
                jqueryCdnPath).Include(
                "~/Scripts/jquery-{version}.js"));
}

And then the fallback if the CDN fails:

@Scripts.Render("~/bundles/jquery")

<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> 

Outras dicas

I don't think it is a waste, the minification feature alone should help improve client response. But it does depend on your js,css,ect in your web app. Browsers are limited to six simultaneous connections. So if your webpage has six or less client side files, it might not make sense to use a ScriptBundle. But since most sites have a good amount of javascript and css, the minification feature of the ScriptBundle make be worth it. This will greatly reduce the amount of KB sent to the user. You can always disable it and see how much of a load these files are for your app.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top