开发者

Minify inline javascript during build for ASP.net?

开发者 https://www.devze.com 2022-12-14 12:08 出处:网络
We have a handful of ASP.net pages that include more than 50+ lines of javascript specific to that page. We\'d like to minify that javascript during our CruiseControl build process.

We have a handful of ASP.net pages that include more than 50+ lines of javascript specific to that page. We'd like to minify that javascript during our CruiseControl build process.

We already use the YUI Compressor to compress our full javascript and css files. But we can't figure out how to d开发者_运维知识库o the Inline javascript.

Is there an MSBuild task to spin through asp.net pages and minify the javascript?


There is an interesting blog and NuGet package called undleMinifyInlineJsCss to handle this

http://weblogs.asp.net/imranbaloch/archive/2012/07/25/bundling-and-minifying-inline-css-and-js.aspx


I would extract javascript into methods and move them into .js files. and call the functions instead with the relevant parameters from the pages. Not a complicated procedure and much easier to maintain (less code). You can also benefit from client side content caching.


Also: Not sure if it helps but Google's Closure looks really good.

http://code.google.com/closure/

Compression options: http://code.google.com/closure/compiler/docs/api-tutorial3.html

Available as Java executable or web service.


You won't be able to do this without custom coding. Easiest way would probably to create a PreBuild step in the msbuild file which spits through all the .aspx files and regexes all the javascript out. Then use YUI to minify the content and replace the original by the minified version.

You might also want to check MbCompression which compresses alot including your asp.net pages, although I don't believe it also minifies the inline javascript.


It is possible to bundle and minify inline javascript. With templated Razor helpers you could create an extension method like the one below:

public static MvcHtmlString AddScriptSource(this HtmlHelper helper, Func<dynamic, HelperResult> source, string key)
{
    string scriptSource = source(null).ToHtmlString();

    // Cache scriptSource here

    return MvcHtmlString.Empty;
}

Which you would use like this:

@Html.AddScriptSource(@<text>$(document).ready(function() { $('h1').text('The current controller is @ViewContext.RouteData.Values["controller"].ToString()'); });</text>, "test")

I created a bundler and minifier around this a few weeks ago at:

https://github.com/philpeace/CodePeace.StrawberryJam


ASP.NET now has bundling and minification built in as of MVC 4 (it is also available for web forms and web pages as well)

http://www.asp.net/mvc/tutorials/mvc-4/bundling-and-minification

0

精彩评论

暂无评论...
验证码 换一张
取 消