Much as I like MVC, so much I don't understand bundling. I read several documents about bundling, but I did not find a general concept until now how to use it for my scripts and styles.
The only solution that works consistently after many hours of trial and error, is:
Create bundle for script x.js with relative path a/b/c as:
var bundle = new ScriptBundle("~/a/b/c/bundle").Include("~/a/b/c/x.js");
bundles.Add(bundle);
Create bundle for style x.css with relative path a/b/c as:
var bundle = new StyleBundle("~/a/b/c/bundle").Include("~/a/b/c/x.css");
bundles.Add(bundle);
And reference it in Views as
@Scripts.Render("~/a/b/c/bundle");
@Styles.Render(("~/a/b/c/bundle");
Obviously the drawback is that for every path I need a single bundle with a key that is constructed as "path" + postfix (I use "bundle" but everything else would also do).
My path look as:
Content\
Scripts
Is there any clever way / best practice how to create and use bundles or to organize the path for scripts and styles?
Comment: I don't see this question as duplicate of How to Bundle and render scripts in mvc 4 -- asp.net? also when the titles as quite similar.
Bundling and minification improves the load time by reducing the number of requests to the server and reducing the size of requested assets (such as CSS and JavaScript). You can create a single bundle for all your CSS but grouping vendor related and custom content separately, increases the manageability. The bundle is treated as single CSS/Javascript file and will require one request although the time it takes to load will increase. To reduce the load time, think about minifying the bundle contents by adding the following
BundleTable.EnableOptimizations = true;
in your bundle registration method.
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
BundleTable.EnableOptimizations = true;
}
Using CDN for Jquery and other standard CSS/Javascripts is a good approach as the content loads parallel from different servers.
http://www.asp.net/mvc/overview/performance/bundling-and-minification
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With