JS脚本优化技术

1.下面这两张图显示的是 调用的同样的JS 所请求需要的时间。。。
图片1

图片2

 1 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="NewOADemo1.WebForm1" %>
 2 
 3 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 4 <html xmlns="http://www.w3.org/1999/xhtml">
 5 <head runat="server">
 6     <title></title>
 7     <script src="Scripts/jquery-1.4.1-vsdoc.js" type="text/javascript"></script>
 8     <script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
 9     <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
10     <script src="Scripts/aOne.js" type="text/javascript"></script>
11     <script src="Scripts/bTwo.js" type="text/javascript"></script>
12     <script src="Scripts/cThree.js" type="text/javascript"></script>
13 </head>
14 <body>
15     <script language="javascript" type="text/javascript">
16         jQuery(document).ready(function () {
17             showHelloWorldAjs(jQuery("#lblAjs"));
18             showHelloWorldBjs(jQuery("#lblBjs"));
19             showHelloWorldCjs(jQuery("#lblCjs"));
20         });
21     </script>
22     <form id="form1" runat="server">
23     <div>
24         <asp:Label ID="lblAjs" runat="server" Text="lblAjs"></asp:Label><br />
25         <asp:Label ID="lblBjs" runat="server" Text="lblBjs"></asp:Label><br />
26         <asp:Label ID="lblCjs" runat="server" Text="lblCjs"></asp:Label>
27     </div>
28     </form>
29 </body>
30 </html>
 1 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" Inherits="NewOADemo1.WebForm2" %>
 2 
 3 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 4 
 5 <html xmlns="http://www.w3.org/1999/xhtml">
 6 <head runat="server">
 7     <title></title>
 8     <script src="Scripts/NewOADemo_20140307.myjs" type="text/javascript"></script>
 9 </head>
10 <body>
11     <script language="javascript" type="text/javascript">
12         jQuery(document).ready(function () {
13             showHelloWorldAjs(jQuery("#lblAjs"));
14             showHelloWorldBjs(jQuery("#lblBjs"));
15             showHelloWorldCjs(jQuery("#lblCjs"));
16         });
17     </script>
18     <form id="form1" runat="server">
19     <div>
20         <asp:Label ID="lblAjs" runat="server" Text="lblAjs"></asp:Label><br />
21         <asp:Label ID="lblBjs" runat="server" Text="lblBjs"></asp:Label><br />
22         <asp:Label ID="lblCjs" runat="server" Text="lblCjs"></asp:Label>
23     </div>
24     </form>
25 </body>
26 </html>
  1 using System;
  2 using System.Collections.Generic;
  3 using System.Linq;
  4 using System.Web;
  5 using System.Text;
  6 using System.IO;
  7 using Yahoo.Yui.Compressor;
  8 using System.Configuration;
  9 namespace NewOADemo1.Common
 10 {
 11     public class GenJsCssHandler
 12     {
 13 
 14         public void SetClientCaching(HttpResponse response, DateTime lastModified)
 15         {
 16             response.Cache.SetETag(lastModified.Ticks.ToString());
 17             response.Cache.SetLastModified(lastModified);
 18             //public 以指定响应能由客户端和共享(代理)缓存进行缓存。      
 19             response.Cache.SetCacheability(HttpCacheability.Public);
 20             //是允许文档在被视为陈旧之前存在的最长绝对时间。      
 21             response.Cache.SetMaxAge(new TimeSpan(7, 0, 0, 0));
 22             //将缓存过期从绝对时间设置为可调时间      
 23             response.Cache.SetSlidingExpiration(true);
 24         }
 25 
 26 
 27         public void PushOut(HttpRequest request, HttpResponse response, CacheItem cacheItem)
 28         {
 29             response.Write(cacheItem.Content);
 30             if (request.Headers["If-Modified-Since"] != null && TimeSpan.FromTicks(cacheItem.Expires.Ticks - DateTime.Parse(request.Headers["If-Modified-Since"]).Ticks).Seconds < 100)
 31             {
 32                 response.StatusCode = 304;
 33 
 34                 response.StatusDescription = "Not Modified";
 35             }
 36             else
 37             {
 38                 SetClientCaching(response, DateTime.Now);
 39             }
 40         }
 41     }
 42 
 43     public class CacheItem
 44     {
 45         public string Content { set; get; }
 46         public DateTime Expires { set; get; }
 47     }
 48 
 49     public class JsHander : GenJsCssHandler, IHttpHandler
 50     {
 51         public bool IsReusable
 52         {
 53             get
 54             {
 55                 return true;
 56             }
 57         }
 58 
 59         public void ProcessRequest(HttpContext context)
 60         {
 61             context.Response.ContentType = "text/javascript";
 62             HttpRequest request = context.Request;
 63             HttpResponse response = context.Response;
 64             string href = context.Request.RawUrl.Trim();
 65             string filePath = string.Empty;
 66             string cacheKey = href;
 67 
 68             try
 69             {
 70                 #region 指定主页js压缩缓存
 71                 if (href.ToLower().IndexOf("newoademo_20140307.myjs") != -1)
 72                 {
 73 
 74                     string[] files = 
 75                 {
 76                        "Scripts/jquery-1.6.4.js"
 77                         ,"Scripts/jquery.cookie.js"
 78                         ,"Scripts/jquery.validate.js"
 79                         ,"Scripts/aOne.js"
 80                         ,"Scripts/bTwo.js"
 81                         ,"Scripts/cThree.js"  
 82                 };
 83                     CacheItem cacheItem = HttpRuntime.Cache.Get(cacheKey) as CacheItem;//服务端缓存  
 84                     if (cacheItem == null)
 85                     {
 86                         string content = string.Empty;
 87 
 88                         StringBuilder sb = new StringBuilder();
 89 
 90 
 91                         foreach (string fileName in files)
 92                         {
 93 
 94 
 95                             if (string.IsNullOrEmpty(ConfigurationManager.AppSettings["virtualPhyPath"]))
 96                             {
 97 
 98                                 filePath = context.Request.PhysicalApplicationPath + fileName.Trim();
 99                             }
100                             else
101                             {
102 
103                                 filePath = ConfigurationManager.AppSettings["virtualPhyPath"] + fileName.Trim();
104                             }
105 
106                             if (File.Exists(filePath))
107                             {
108                                 string readstr = File.ReadAllText(filePath, Encoding.UTF8);
109                                 sb.Append(readstr);
110                                 sb.Append("  ; ");
111 
112                             }
113                             else
114                             {
115                                 sb.AppendLine("\r\n未找到源文件" + filePath + "\r\n");
116                             }
117                         }
118                         content = sb.ToString();
119                         JavaScriptCompressor js = new JavaScriptCompressor();
120                         content = js.Compress(content);
121 
122                         cacheItem = new CacheItem() { Content = content, Expires = DateTime.Now.AddHours(1) };
123                         HttpRuntime.Cache.Insert(cacheKey, cacheItem, null, cacheItem.Expires, TimeSpan.Zero);
124                     }
125                     PushOut(request, response, cacheItem);
126                 }
127                 #endregion
128 
129                 # region 单个文件
130                 else if (href.IndexOf(",") == -1)
131                 {
132 
133                     CacheItem cacheItem = HttpRuntime.Cache.Get(cacheKey) as CacheItem;
134                     if (cacheItem == null)
135                     {
136                         StringBuilder sb = new StringBuilder();
137 
138 
139                         if (!File.Exists(context.Request.PhysicalPath))
140                             return;
141                         string content = "";
142                         string readstr = File.ReadAllText(context.Request.PhysicalPath, Encoding.UTF8);
143                         sb.Append(readstr);
144                         response.Write(content); cacheItem = new CacheItem() { Content = content, Expires = DateTime.Now.AddHours(1) };
145                         HttpRuntime.Cache.Insert(cacheKey, cacheItem, null, cacheItem.Expires, TimeSpan.Zero);
146                     }
147                     PushOut(request, response, cacheItem);
148 
149                 }
150 
151 
152                 #endregion
153             }
154             catch (Exception ex)
155             {
156                 var s = File.CreateText(@"d:\abc\logJs" + Guid.NewGuid().ToString() + ".txt");
157                 s.WriteLine(filePath);
158                 s.WriteLine(ex.Message);
159                 s.Flush();
160                 s.Close();
161             }
162         }
163 
164 
165     }
166 }
 1 <?xml version="1.0"?>
 2 
 3 <!--
 4   有关如何配置 ASP.NET 应用程序的详细信息,请访问
 5   http://go.microsoft.com/fwlink/?LinkId=169433
 6   -->
 7 
 8 <configuration>
 9   <connectionStrings>
10     <add name="ApplicationServices"
11          connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true"
12          providerName="System.Data.SqlClient" />
13   </connectionStrings>
14 
15   <appSettings>
16     <add key="virtualPhyPath" value=""/>
17   </appSettings>
18 
19   <system.web>
20     <compilation debug="true" targetFramework="4.0" />
21 
22     <authentication mode="Forms">
23       <forms loginUrl="WebForm1.aspx" timeout="2880" />
24     </authentication>
25 
26     <httpHandlers>
27       <add verb="GET" path="NewOADemo_20140307.myjs" type="NewOADemo1.Common.JsHander,NewOADemo1"></add>
28       <!--<add verb="*" path="*.htm" type="URLRewriter.RewriterFactoryHandler,URLRewriter"/>-->
29     </httpHandlers>
30 
31     <membership>
32       <providers>
33         <clear/>
34         <add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices"
35              enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false"
36              maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10"
37              applicationName="/" />
38       </providers>
39     </membership>
40 
41     <profile>
42       <providers>
43         <clear/>
44         <add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/"/>
45       </providers>
46     </profile>
47 
48     <roleManager enabled="false">
49       <providers>
50         <clear/>
51         <add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="ApplicationServices" applicationName="/" />
52         <add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" />
53       </providers>
54     </roleManager>
55 
56   </system.web>
57 
58   <system.webServer>
59     <modules runAllManagedModulesForAllRequests="true"/>
60   </system.webServer>
61 </configuration>

 

posted @ 2014-04-03 09:56  Jbp  阅读(346)  评论(1)    收藏  举报