many online compression CSS and JS tools, but there is always something special in our system. You may find it difficult to use a third-party compression tool. I have encountered this problem. I don't want to compress locally, I just want to update to the server for compression, and I don't need to perform backup or other operations. So I thought about implementing the compression tool myself.
initial requirements:
- use Yahoo. Yui. Compressor 2.0
- only compress CSS and JS files in the specified folder in the website directory.
- jquery plug-in is used, so many JavaScript files are compressed. Therefore, do not compress min stored in the file name
- file backup not required
- If the file is compressed during the first access or the Program is compressed at startup?
implementation (the compressed version is started by the Application):
- reference Yahoo. Yui. compressor. dll
- in global. add Code to the application_start event of asax -- code:
VaR files = system. Io. Directory. getfiles (server. mappath ("~ /"),"*. * ", Searchoption. alldirectories); foreach (var file in files) {fileinfo finfo = new fileinfo (File); // todo you can add files in the folder to record the last compression time. the last modification time of the file is determined after the last compression time. in addition, asynchronous processing of string strcontent = file can also be performed here. readalltext (file, encoding. utf8); // if the name is not min // todo, you may need to better judge if (! File. contains (". min. ") {// cancel the File Read-Only file. setattributes (file, fileattributes. normal); If (finfo. extension. tolower () = ". JS ") {// initialize JS compression class var JS = new javascriptcompressor (); Js. compressiontype = compressiontype. standard; // compression type Js. encoding = encoding. utf8; // code Js. ignoreeval = false; // case-insensitive conversion Js. threadculture = system. globalization. cultureinfo. currentculture; // compress the JS strcontent = Js. compress (strcontent); file. writealltext (file, strcontent, encoding. utf8);} else if (finfo. extension. tolower () = ". CSS ") {// perform CSS compression csscompressor CSS = new csscompressor (); strcontent = CSS. compress (strcontent); file. writealltext (file, strcontent, encoding. utf8 );}}}
Download complete code: Http://files.cnblogs.com/xuchengzone/JS-CSS.Compressor.rar