Manage js and css resources and integrate with YUI compressor
The javascript file and css files are hard to be managed. On one side, we want to keep them in different files according to the module and reuse it between pages. On the other side, the scripts and styles should be merged into one or two files to decrease the number of http requests.
This is the reason that I wrote a resource management module in my personal web project. This is what i want,
- web app has several themes, and each theme has several sites. the site can overrides/extends the resource file of theme.
- easy to config. a simple line in properties file could redirect the request to another one or more files bundle.
- manage different resource types, which are located in different directories. and only the javascript (maybe also css later) should be compressed by YUI compressor.
- gzip, etag, last-modified in http response header.
- cache for live environment and no cache for development env.
There’re some difficult points or maybe just I don’t know it before.
- To get the resources, ServletContext should be used, but getResourceAsStream(…):InputStream can only get the bytes, not the file meta information. The getResource(…):URL is the solution. Even the resources can be located in local or remote file system, a war package, or in a jndi url. But the specification also said it will always return a object which implemented the corresponding URLConnection. then the meta info can be retrieved there.
- YUI compressor depends and rewrites some class of Mozilla Rhino. Unfortunately, rhino is usually be included in the jre. The solution from Yahoo is to use a custom-built ClassLoader which will load the rewritten class files in the jar package. However, for the web project, it’s not so easy to it because the jar package can be in anywhere, in a war, database and hell. And this is also heavy loaded because the zip file will be processed quite many times. My solution is to use the source files of YUI compressor, not the binary package. And rewrite my own ClassLoader, which will load mozilla classes correctly. It’s damn easy then.
BTW, my next step is write a css compressor. not like the YUI one, i want something can create the short alias for the css class and id. It’s really cool and I will share it when i finished.
on June 30th, 2010 | No Comments »
