简体   繁体   中英

Minify dynamically generated javascript at runtime for ASP.NET

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?

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.

PS 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM