Reputation: 1337
In trying to keep with unobtrusive JavaScript guidelines I moved all the JavaScript out of each of my views and into a separate .js files.
However, within 1 view I need to dynamically create some JavaScript variables so these are inserted into the ViewBag and rendered directly into the view:
$(document).ready(function () {
@(ViewBag.PrePop)
@(ViewBag.PreDiscount)
});
This works fine until I had a go at using the new ASP.net bundling and minification feature.
Bundling all these small external JavaScript files together and then calling the combined script from every page means that every page (other than the one that contains the ViewBag emitted variables) has a variable reference error:
Uncaught ReferenceError: quotes is not defined
So this basically means I can't bundle this particular JavaScript file.
However, I would like to minify it. To do this, do I just declare a bundle that only contains the one JavaScript file:
bundles.Add(new ScriptBundle("~/bundles/mypagescript").Include(
"~/Scripts/mypagescript.js"));
Or is there another way to perform solely minification?
Upvotes: 2
Views: 3091
Reputation: 21
Sorry for the late answer ;)
You can use Microsoft.Ajax.Utilities.Minifier. Create an instance and call MinifyJavaScript - which takes a string (the JS-code) as a parameter and returns the minified code.
Dim minifier As New Microsoft.Ajax.Utilities.Minifier()
minifier.MinifyJavaScript(script)
You could then create your own HTML-helper or action to call for this. This worked well in my case atleast ;)
Upvotes: 2
Reputation: 28200
Yep, currently we don't really expose any methods for you to easily call in to Optimization just to minify a string (you could do it via an instance of JsMinify.Process
if you really wanted) i.e.:
string js = "//I am a comment\r\nfoo = bar;\r\nfoo = yes;";
JsMinify jsmin = new JsMinify();
BundleContext context = new BundleContext();
BundleResponse response = new BundleResponse(js, null);
response.Content = js;
jsmin.Process(context, response);
Assert.AreEqual("foo=bar,foo=yes", response.Content);
But what you suggest is probably best (create a bundle of one file).
Upvotes: 3