简体   繁体   English

缩小ASP.NET在运行时动态生成的JavaScript

[英]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. 我使用.cshtml文件在ASP.NET MVC控制器中生成动态.js文件。 So the .js file never exists on disk, but only in memory at runtime. 因此, .js文件从不存在于磁盘上,而仅在运行时存在于内存中。 It works like this. 它是这样的。

The browsers loads a javascript... 浏览器会加载JavaScript ...

<script async src='http://example.com/script.js'></script>

...that is fetched from and generated by my MVC Controller endpoint: ...是从我的MVC控制器端点获取并生成的:

[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? 有没有办法最小化在运行时返回的结果javascript文件? I had a look at System.Web.Optimization.JsMinify but I'm not sure how I would get that to work. 我看了一下System.Web.Optimization.JsMinify但不确定如何System.Web.Optimization.JsMinify工作。 Can I write some kind of HttpHandler ? 我可以编写某种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 . PS它似乎是Microsoft Ajax Minifier库的一部分,但是我不记得手动安装它,因此它既是MVC的一部分,还是System.Web.Optimization附带的。


I didn't notice the part about the JS being generated from a view. 我没有注意到有关从视图生成JS的部分。 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 . 在那种情况下,使用捆绑包可能是一种解决方案,也可以将视图呈现为string (但是我不熟悉在Spark视图引擎中的处理方式),然后再将其传递给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. 编辑:另一个解决方案(有点费解)是在视图中调用Minifier.MinifyJavaScript并在局部视图中填充实际的JS。 I don't know about Spark , but in Razor it's fairly easy to render a view to string from another view. 我不了解Spark ,但是在Razor中 ,将视图渲染为另一个视图的string相当容易。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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