Merge multiple script references in the web page

  • 2020-05-26 08:18:42
  • OfStack

For better encapsulation, each js code that implements different functions should have its own js file, so that if multiple js files are referenced in one web page, as shown below
 
<script type="text/javascript" src="limit.js"></script> 
<script type="text/javascript" src="select.js"></script> 
<script type="text/javascript" src="rating.js"></script> 

In this way, the web page will send 3 requests to the server, requesting 3 js files. In fact, there is no need to send so many requests. One is enough
Create a new HttpHandler
 
public class Handler1 : IHttpHandler 
{ 
public void ProcessRequest(HttpContext context) 
{// Original link: blog.csdn.net/bluceyoung 
string[] js = context.Request.Url.LocalPath.Substring(1, context.Request.Url.LocalPath.Length - 5).Split('.'); 
StringBuilder sb = new StringBuilder(); 
foreach (string j in js) 
{ 
sb.Append(ReadFile(j+".js")); 
} 
context.Response.Write(CompressStr(sb)); 
} 
private string ReadFile(string fileName) 
{ 
string directory = @"D:\SRC\bluceyoung\"; 
if (!File.Exists(directory + fileName)) 
{ 
return ""; 
} 
string result; 
using (FileStream fs = new FileStream(directory + fileName, FileMode.Open)) 
{ 
using (StreamReader sr = new StreamReader(fs)) 
{ 
result = sr.ReadToEnd(); 
} 
} 
return result; 
} 
private string CompressStr(StringBuilder sb) 
{ 
while (true) 
{ 
int length = sb.Length; 
sb.Replace(" ", " "); 
if (length == sb.Length) 
break; 
} 
sb.Replace("\r\n", "").Replace("\t", "").Replace("; ", ";").Replace(" }", "}").Replace("} ", "}").Replace(" ;", ";").Replace(" {", "{").Replace("{ ", "{"); 
return sb.ToString(); 
} 
public bool IsReusable 
{ 
get 
{ 
return false; 
} 
} 
} 

Add a node to the configuration file
 
<configuration> 
<system.web> 
<compilation debug="true" targetFramework="4.0" /> 
<httpHandlers> 
<add path="*.jsx" verb="*" type="BluceYoung.Handler1"/> 
</httpHandlers><!-- Original blog: blog.csdn.net/bluceyoung --> 
</system.web> 
</configuration> 

Page calls
 
<script src="limit.select.rating.jsx" type="text/javascript"></script> 

In this way, one script reference completes the request for multiple js files and compresses the files

Related articles: