Is it any value of adding one script file to Bundl

2019-08-12 05:33发布

问题:

I am designing a very big application now and i want to make good infrastructure for the future.

In Razor (MVC) there is an option to include javascript files in a view by using the function @Scripts.Render("~/Scripts/myscript.js") by specify a specific file or bundle item from BundleCollection which defined in BundleConfig.cs.

I am wondering, is there any added value to define a bundle item in the Scripts.Render function of only single file instead of specify the script file itself?

one of added value i found is that in the long run i will be able to add more files to the bundle as needed without changing the views that using it and i will enjoy the optimization. but i couldn't find added value for that while i am still using one js file in the "bundle".

回答1:

There is a couple of benefits actually apart from the one you have mentioned:

  1. Bundles are minified in release mode. When you add a file to the bundle (even a single file) and reference the bundle in the view the code will be minified. It's not the case when you reference the file directly. That's most probably what you're going for in production.
  2. The framework generates and appends a random hash to the script with every new version of the bundle to invalidate the cache of the previous bundles. It looks something like this <script src="/bundles/myscript.js?v=CQJxkNd9QnrvutTyUG9mM-vD0FrbCc1"></script>. Your clients will thank you for this after every new release. And again - it doesn't happen if you reference the file directly unless you generate and append the versions manually.

So what I usually do, and I consider it a good practice until I'm proven wrong, I create a bundle for every page specific needs even if it consists of a single js file with a tiny module. For example Home page:

bundles.Add(new ScriptBundle("~/bundles/home").Include("~/Scripts/home.js")); @Scripts.Render("~/bundles/home")