3

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?

Joel
  • 8,502
  • 11
  • 66
  • 115
  • What about [Bundling and Minification](http://www.asp.net/mvc/overview/performance/bundling-and-minification) – Izzy Apr 27 '15 at 12:01
  • @Izzy That's what I'm trying to achieve. But I can' find a way to use that on a dynamically created javascript file. It only exists in memory, not on file. Do you know how to take for example a string containing a javascript, and minify that using Bundling and Minification? – Joel Apr 27 '15 at 12:03

1 Answers1

3

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.

Community
  • 1
  • 1
jahu
  • 5,427
  • 3
  • 37
  • 64