Reputation: 8938
I use a .cshtml
file to generate a dynamic .js
file in an ASP.NET MVC controller. So the .js
file never exists on disk, but only in memory at runtime. It works like this.
The browsers loads a javascript...
<script async src='http://example.com/script.js'></script>
...that is fetched from and generated by my MVC Controller endpoint:
[HttpGet]
[Route("script.js")]
public ActionResult GetScript()
{
// This takes a .cshtml template-file and returns a generated .js file
return new JavascriptViewResult(viewName, viewModel);
}
Is there a way to minify the resulting javascript file that is returned in runtime? I had a look at System.Web.Optimization.JsMinify
but I'm not sure how I would get that to work. Can I write some kind of HttpHandler
? Is there maybe a better approach to solve this problem?
Upvotes: 3
Views: 1764
Reputation: 5657
I had a similar problem and after some searching some I came across this question. All you need to do is:
using Microsoft.Ajax.Utilities;
//...
string minifiedScript = new Minifier().MinifyJavaScript(yourJs);
I can't believe it was this simple, yet so hard to find.
P.S. It seems to be part of Microsoft Ajax Minifier library, but I don't remember ever installing it manually, so it's either part of MVC or comes with System.Web.Optimization
.
I didn't notice the part about the JS being generated from a view. In that case using bundles might be a solution or rendering the view to a string
(but I'm unfamiliar with how it's done in Spark view engine) before passing it to Minifier.MinifyJavaScript
.
Edit: Another solution (albite somewhat convoluted) would be calling Minifier.MinifyJavaScript
in the view and cramming the actual JS in a partial view. I don't know about Spark, but in Razor it's fairly easy to render a view to string
from another view.
Upvotes: 3