How do I add individual css/js files per page through the minification api?
4 Answers
If you just want to add your own, unbundled scripts and use jquery-calls in a MVC 4 application that uses minification and bundling to include the standard libraries, here's an easy way of doing it:
By default the _Layout.chtml includes jquery and then calls
@RenderSection("scripts", required: false)
To add your own scripts that uses jquery to the page, you can add the content for the section like this (in your view):
@section scripts {
// At this point jquery is available. Include your own scripts here
}
Comments
Not to sound too much like a sales man, but you could also look at RequestReduce. You don't really need to create or declare bundles instead whatever js and css you already have on your page is automatically bundled and minified. One advantage here is if different pages have different combinations of js and css, each unique combination is made into a "bundle" by RequestReduce but you dont have to manage it. Everything is cached so there is no need to worry about runtime perf costs.
2 Comments
My understanding is that you can setup separate bundles that consist of different files. Then, you can includes these bundles in certain pages. There is information on it here. I think what you are looking for is addressed in the "custom rules" section.
You asked how to do it from the controller. I don't think there is a facility for that. From reading the post, it looks like you setup the custom bundles in the global.asax and then reference that custom bundle from each view you want it to be a part of.
For example, in your globabl.asax, you could do this:
var b = new Bundle("~/CustomBundle", new JsMinify());
b.AddFile("~/scripts/knockout.js");
BundleTable.Bundles.Add(b);
Then in your view, you could do this:
<script src="@Url.Content("~/CustomBundle")" type="text/javascript"></script>
I've tried this out and it looks like it works just fine.
Another possibility is to use Cassette. It looks to be a little more advanced at the moment although that could change when MVC 4 is released.
Comments
Scott Guthrie's blog has a video of him walking through how to set up minification in mvc4. It's a lot of good info.