Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to correctly bundle styles and scripts in MVC 4?

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:

  1. 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);
    
  2. 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\

    • Calendar\
    • DatePicker\
    • JqGrid\
    • Template\
      • FontAwesome\
    • ...
  • Scripts

    • DayPilot
    • jqGrid
    • jqPlot
    • ...

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.

like image 420
StefanG Avatar asked Dec 19 '15 19:12

StefanG


1 Answers

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

like image 183
DevGuru Avatar answered Nov 11 '22 23:11

DevGuru