做web前段也有一段时间了,对于web中js文件的加载有些体会想跟大家一起分享一下。
1.首先说说js文件的合并和压缩吧
为了便于集中式管理js的合并和压缩我们创建一个Js.ashx文件来专门处理合并压缩,这里我们借用Yahoo.Yui.Compressor工具来压缩我们的js文件
代码如下:
public class Js : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/javascript";
HttpRequest request = context.Request;
HttpResponse response = context.Response;
if (!request.QueryString.AllKeys.Contains("href"))
{
response.Write("No Content");
}
else
{
string href = context.Request.QueryString["href"].Trim();
string[] files = href.Split(new string[]{",",","},StringSplitOptions.RemoveEmptyEntries);
foreach (string fileName in files)
{
string filePath = context.Server.MapPath(fileName);
if (File.Exists(filePath))
{
string content = File.ReadAllText(filePath, Encoding.UTF8);
content = JavaScriptCompressor.Compress(content);
response.Write(content);
}
else
{
response.Write("\r\n未找到源文件"+filePath+"\r\n");
}
}
}
}
public bool IsReusable
{
get
{
return false;
}
}
}当我们在浏览器访问js时如:
http://localhost:58798/js.ashx?href=scripts/jquery.lazyload.js,scripts/jquery.validate.js
返回结果如图:

本文探讨了Web前端JS文件的优化方法,包括通过Js.ashx进行JS合并和压缩,避免重复引用,以及利用lazyload.js实现延迟加载,提高页面加载速度。同时,介绍了如何设置客户端缓存以实现304响应,提升用户体验。
最低0.47元/天 解锁文章

被折叠的 条评论
为什么被折叠?



