There are two versions of the functionality: the simple, automatic way; and the much more useful custom approach. In the simple version, the contents of folders are automatically bundled and minified if your <link> and <script> tags to point at the default directories and don’t specify individual files, thus:
<link href=”/Content/css” rel=”stylesheet” type=”text/css” />
That gets converted into html along these lines at runtime:
<link rel=”stylesheet” type=”text/css” href=“/Content/themes/base/css?v= UM624qf1uFt8dYtiIV9PCmYhsyeewBIwY4Ob0i8OdW81″ />
That’s fine as far as it goes, but is also rather limiting. You have to use default locations, and there’s no scope for having different bundles for different versions of your application. In my www.cocktailsrus.com site, I have two distinct versions, for mobile and standard browsers, each of which requires different .css and .js files, so I need to be able to create custom bundles.
The MVC4 template comes with a feature that’s designed to support this – ResolveBundleUrl():
<link href=”@System.Web.Optimization.BundleTable.Bundles.ResolveBundleUrl (“~/Content/css”)“ rel=”stylesheet” type=”text/css” />
Now we can define our own custom bundles. In my case, I can create two new sub-folders under the style and script paths, one for mobiles and one for the standard Web site:
Then I change the paths passed to ResolveBundleUrl() to point at my new folders….
<link href=”@System.Web.Optimization.BundleTable.Bundles.ResolveBundleUrl(“~/Content/site/css”)“ rel=”stylesheet” type=”text/css” />
and… it doesn’t work.
Although ResolveBundleUrl() supports adding non-default paths, you have to do a little more work and register your new paths in the application start event in the Global.asax before it can use those paths.
This tells the system that we’re adding two bundles – one for .css files and one for .js, and that all the files in the specified directories should be part of the bundle. (You can also specify individual files if you need to control the loading order beyond the default settings, which first prioritize known libraries like jQuery, then load the files alphabetically).
For related information, check out these courses from Learning Tree: