Web Front-end Optimization-new series (2)
Source: http://www.cnblogs.com/_popc
Introduction: at present, we can see that many Internet websites use js merge compression for web Front-end optimization. The landlord found several addresses for Reference
Address 1 and address 2
The following describes how to implement it.
1. to merge and compress js data, you must first construct a link address as shown in the above link.
@using MvcApplication.ExtensionsFolder
Then let's take a look at the implementation of the Extension Method LoadJsList for the MvcHtmlString class. The use of extension methods in mvc is quite common.
public static MvcHtmlString LoadJsList(this HtmlHelper htmlhelp, string ListJs) { StringBuilder sb = new StringBuilder(); string jsFormat = "<script type=\"text/javascript\" src=\"{0}\"></script>"; sb.AppendFormat(jsFormat, JsHandlerUrl + ListJs); return new MvcHtmlString(sb.ToString()); }
2. In this case, the output page is
<script type="text/javascript" src="http://localhost:1309/ashx/MergerJsHandler.ashx?href=jquery-1.4.4.min.js,jquery-ui.js,MicrosoftAjax.js&v=20121222"></script>
So far, we have completed half of the work, and the next step is to output the merged and compressed js.
3. In the MergerJsHandler. ashx File
private string JsHandlerUrl { get { return ConfigurationManager.AppSettings["jsAddress"] ?? string.Empty; } } public void ProcessRequest(HttpContext context) { //"http://localhost:1309/ashx/MergerJsHandler.ashx?href=jquery-1.4.4.min.js,domestic.js,v=20121222 context.Response.ContentType = "text/plain"; HttpRequest request = context.Request; HttpResponse response = context.Response; if (!context.Request.QueryString.AllKeys.Contains("href")) { response.Write("error"); } else { string[] filesName = request.QueryString["href"].Trim().Split(new string[] { ","}, StringSplitOptions.RemoveEmptyEntries); Compress(request.QueryString["v"], context, filesName); } }
Is to obtain the parameters and then call the compress method for processing and output.
Compression I use Yahoo. Yui. Compressor. This compression tool can both compress js and compress css.
/// <Summary> ///// </summary> /// <param name = "v"> indicates whether to modify </param> /// <param name = "context"> current context </param> private void Compress (string v, httpContext context, string [] jsPar) {StringBuilder sb = new StringBuilder (); var SaveJsFilePath = ConfigurationManager. appSettings ["jsAddress"]? String. Empty; var files = System. IO. Directory. GetFiles (context. Server. MapPath ("~ /") + SaveJsFilePath, v, SearchOption. TopDirectoryOnly); if (files! = Null & files. length> 0) // if it exists, the Compressed content {var content = File is directly output. readAllText (files [0], Encoding. UTF8); sb. append (content);} else // obtain and compress each js, save and output {foreach (var file in jsPar) {var path = context. server. mapPath ("~ /") + JsHandlerUrl + file; FileInfo finfo = new FileInfo (JsHandlerUrl + file); string strContent = File. readAllText (path, Encoding. UTF8); // cancel the File Read-Only File. setAttributes (path, 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; // large Lowercase conversion js. threadCulture = System. globalization. cultureInfo. currentCulture; // compress the js strContent = js. compress (strContent); sb. append (strContent); // else if (finfo. extension. toLower () = ". css ") // {// perform CSS compression // CssCompressor css = new CssCompressor (); // strContent = css. compress (strContent); // File. writeAllText (file, strContent, Encoding. UTF8); //} File. writeAllText (context. server. mapPath (" ~ /") + SaveJsFilePath + v, sb. ToString (), Encoding. UTF8);} context. Response. Write (sb. ToString ());}
Then the printed code is processed successfully.
This is all done. Of course, the above parameters are not considered for filtering and so on. In actual development, filtering and some malicious requests all need to be processed. After all, the landlord still hasn't used them in actual development, but the difference is not far away. Haha.
Finally, let's look at the effect.
However, I have a problem: the size of the merge request is larger than that of the three independent JavaScript files. Is it because the request parameters and request headers are tricky.