使用Yahoo.Yui.Compressor實現網站css、js的壓縮
使用說明:css
1:
2: protected void Application_Start(object sender, EventArgs e)
3: {
4: var files = System.IO.Directory.GetFiles(Server.MapPath("~/"), "*.*", SearchOption.AllDirectories);
5: foreach (var file in files)
6: {
7: FileInfo finfo = new FileInfo(file);
8: //todo 你能夠在文件夾添加能夠文件記錄最後壓縮時間.再判斷文件最後修改時間是在上一次壓縮時間以後的文件.並且這裏還能夠作異步處理
9:
10: string strContent = File.ReadAllText(file, Encoding.UTF8);
11: //名稱不是min
12: //todo 可能須要更完善的判斷
13: if (!file.Contains(".min."))
14: {
15: //取消文件只讀
16: File.SetAttributes(file, FileAttributes.Normal);
17: if (finfo.Extension.ToLower() == ".js")
18: {
19: //初始化JS壓縮類
20: var js = new JavaScriptCompressor();
21: js.CompressionType = CompressionType.Standard;//壓縮類型
22: js.Encoding = Encoding.UTF8;//編碼
23: js.IgnoreEval = false;//大小寫轉換
24: js.ThreadCulture = System.Globalization.CultureInfo.CurrentCulture;
25: //壓縮該js
26: strContent = js.Compress(strContent);
27:
28: File.WriteAllText(file, strContent, Encoding.UTF8);
29: }
30: else if (finfo.Extension.ToLower()==".css")
31: {
32: //進行CSS壓縮
33: CssCompressor css = new CssCompressor();
34: strContent = css.Compress(strContent);
35: File.WriteAllText(file, strContent, Encoding.UTF8);
36: }
37: }
38: }
39: }
以上代碼只是測試代碼,用於生產環境須要簡單修改,不少能夠改進的我已經在註釋裏面標記出來了app
完整代碼下載異步