开发者

How to minify different javascript files at runtime using Java

开发者 https://www.devze.com 2023-03-01 22:28 出处:网络
I\'m trying to build (or find an existing one I can use) a web filter that will compress a JavaScript file at runtime. I\'ve tried building one based on YUICompressor, b开发者_运维百科ut I\'m getting

I'm trying to build (or find an existing one I can use) a web filter that will compress a JavaScript file at runtime. I've tried building one based on YUICompressor, b开发者_运维百科ut I'm getting weird errors out of it when I try and pass a String based source into it instead of an actual file.

Now I'm expecting to get bombarded with responses like 'Real time compression/minification is a bad idea' but there is a reason I'm not wanting to do it at build time.

I've got a JavaScript web application that lazy loads it's JavaScript. It will only load what it actually needs. The JavaScript files can specify dependencies and I already have a filter that will concatenate the requested files and any dependencies not already loaded into a single response. This means that there is a large number of different combinations in the JavaScript that will be sent to the user which makes trying to build all the bundles at build time impractical.

So to restate. Ideally I'm looking for an existing real time javascript filter I can just plug into my app.

If one doesn't exist I'm looking for tips on what I can use as building blocks. YUICompressor hasn't quite got me there and GoogleClosure seems to only be a web API.

Cheers, Peter


Take a look at The JavaScript Minifier from Douglas Crockford. The source is here: JSMin.java. It's not a filter and only contains the code to minify. We've made it into a filter where we combine and minify JavaScript on the fly as well. It works well, especially if you have browsers and a CDN cache results.

Update: I left out that we cache them on the server too. They're only regenerated if any of the assets required to make the combined and minified output have changed. Basically instead of "compiling" them at build time, we handle each combination once at runtime.


I already have a filter that will concatenate the requested files and any dependencies not already loaded into a single response

Sooo.. Why not just minify those prior to loading/concatenating them?

(And yes, compression on the fly is horribly expensive and definitely not worth doing for every .js file served up)

0

精彩评论

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