js文件合并,压缩,缓存,延迟加载
做web前段也有一段时间了,对于web中js文件的加载有些体会想跟大家一起分享一下。
1.首先说说js文件的合并和压缩吧
为了便于集中式管理js的合并和压缩我们创建一个Js.ashx文件来专门处理合并压缩
代码如下:
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);
}
}
}
} public bool IsReusable
{
get
{
return false;
}
}
}
返回结果如图:
但是在实际开发中很多项目为了最求js的合并和压缩,开发很不友好把js的引用放在一个地方,写了很长的一串啊,如上面js引用。
下面说说如何改善吧:
public static class Extensions
{
const string jsFileKey = "JSFileKey";
static string jshandlerUrl = string.Empty;
public static string JsHandlerUrl
{
get
{
if (string.IsNullOrEmpty(jshandlerUrl))
{
jshandlerUrl = ConfigurationManager.AppSettings["jsHandlerUrl"] ?? string.Empty;
}
return jshandlerUrl;
}
} public static void AppendJsFile(this HtmlHelper htmlHelper, string jsFile, int group = 1)
{
NameValueCollection jsFiles = null;
if (htmlHelper.ViewContext.HttpContext.Items.Contains(jsFileKey))
{
jsFiles = htmlHelper.ViewContext.HttpContext.Items[jsFileKey] as NameValueCollection;
}
else
{
jsFiles = new NameValueCollection();
htmlHelper.ViewContext.HttpContext.Items.Add(jsFileKey, jsFiles);
}
if (jsFiles.AllKeys.Contains(group.ToString()))
{
string fileUrl = jsFiles[group.ToString()];
if (!fileUrl.Contains(jsFile))
jsFiles.Add(group.ToString(), jsFile);
}
else
{
jsFiles.Add(group.ToString(), jsFile);
} htmlHelper.ViewContext.HttpContext.Items[jsFileKey] = jsFiles;
} public static MvcHtmlString RenderJsFile(this HtmlHelper htmlHelper)
{
NameValueCollection jsFiles = null;
StringBuilder content = new StringBuilder();
if (htmlHelper.ViewContext.HttpContext.Items.Contains(jsFileKey))
{
jsFiles = htmlHelper.ViewContext.HttpContext.Items[jsFileKey] as NameValueCollection;
List<string> jsKeys = jsFiles.AllKeys.OrderBy(x => x).ToList<string>(); string jsFormat = "<script type="text/javascript" src="{0}"></script>";
foreach (string key in jsKeys)
{
string jsFile = jsFiles[key];
content.AppendFormat(jsFormat, JsHandlerUrl + jsFile);
//htmlHelper.ViewContext.HttpContext.Response.Write(string.Format(jsFormat, JsHandlerUrl + jsFile));
}
}
return new MvcHtmlString(content.ToString());
}
}
这样在开发的时候我们书写代码就很方便了如:
[csharp]
@{Html.AppendJsFile("Scripts/jquery.lazyload.js");}
下面我们来看看js的延迟加载,为了实现js延迟加载我们需要引用相关的js,在这里我用的是lazyload.js,具体请参考http://www.2cto.com/kf/201205/130023.html
延迟加载后的效果
在文档加载前只加载了一个2.2k的lazyload.js文件,其他的js文件都在ready后加载。
下面再来看看js的缓存吧,缓存涉及到要做服务端和客户端缓存
修改后的代码:
class CacheItem
{
public string Content { set; get; }
public DateTime Expires { set; get; }
}
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);
CacheItem item = null;
object obj = HttpRuntime.Cache.Get(href);//服t务?端?缓o存?
if (null == obj)
{
StringBuilder allText = new StringBuilder();
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);
allText.Append(content);
}
else
{
// response.Write("rn未找到源文件"+filePath+"rn");
allText.Append("rn未找到源文件" + filePath + "rn");
}
}//end foreach
item = new CacheItem() { Content = allText.ToString(), Expires = DateTime.Now.AddHours(1) };
HttpRuntime.Cache.Insert(href, item, null, item.Expires, TimeSpan.Zero);
}
else
{
item = obj as CacheItem;
}
if (request.Headers["If-Modified-Since"] != null && TimeSpan.FromTicks(item.Expires.Ticks - DateTime.Parse(request.Headers["If-Modified-Since"]).Ticks).Seconds < 100)
{
response.StatusCode = 304;
// response.Headers.Add("Content-Encoding", "gzip");
response.StatusDescription = "Not Modified";
}
else
{
response.Write(item.Content);
SetClientCaching(response, DateTime.Now);
}
}//end else href
}
private void SetClientCaching(HttpResponse response, DateTime lastModified)
{
response.Cache.SetETag(lastModified.Ticks.ToString());
response.Cache.SetLastModified(lastModified);
//public 以指定响应能由客户端和共享(代理)缓存进行缓存。
response.Cache.SetCacheability(HttpCacheability.Public);
//是允许文档在被视为陈旧之前存在的最长绝对时间。
response.Cache.SetMaxAge(new TimeSpan(7, 0, 0, 0));
//将缓存过期从绝对时间设置为可调时间
response.Cache.SetSlidingExpiration(true);
}
}
运行效果如图:

代码下载地址:http://www.2cto.com/uploadfile/2012/0503/20120503021534861.zip
js文件合并,压缩,缓存,延迟加载的更多相关文章
- gulp 之一 安装及简单CSS,JS文件合并压缩
最近研究了一下gulp构建工具,发现使用起来比grunt顺手一些.(个人感受),以下是grunt和gulp构建方式和原理: grunt 基于文件方式构建,会把文件先写到临时目录下,然后进行读文件,修改 ...
- 使用System.Web.Optimization对CSS和JS文件合并压缩
在ASP.NET MVC 中JS/CSS文件动态合并及压缩通过调用System.Web.Optimization定义的类ScriptBundle及StyleBundle来实现. 大致步骤如下: 1.A ...
- AngularJS结合RequireJS做文件合并压缩的那些坑
我在项目使用了AngularJS框架,用RequireJS做异步模块加载(AMD),在做文件合并压缩时,遇到了一些坑,有些只是解决了,但不明白原因. 那些坑 1. build.js里面的paths必须 ...
- 【JS代码压缩】使用YUI Compressor对js文件进行压缩处理
概述 在使用html5开发Hybird APP的时候,可能会引入大量的js包,另外对于一些核心的js文件,进行一些特殊的处理, 如压缩和加密就显得很重要了,YUI Compressor就是这样一个用于 ...
- 编写gulpfile.js文件:压缩合并css、js
使用gulp一共有四个步骤: 1. 全局安装 gulp: $ npm install --global gulp 2. 作为项目的开发依赖(devDependencies)安装: $ npm inst ...
- 前端js文件合并三种方式
最近在思考前端js文件该如何合并,当然不包括不能合并文件,而是我们能合并的文件,想了想应该也只有三种方式. 三个方式如下: 1. 一个大文件,所有js合并成一个大文件,所有页面都引用它. 2. 各个页 ...
- CSS 和 JS 文件合并工具
写 CSS 和 JavaScript 的时候, 我们会遇到一个两难的局面: 要么将代码写在一个大文件, 要么将代码分成多个文件. 前者导致文件难以管理, 代码复用性差, 后者则因为需要在载入多个文件令 ...
- RequireJS 文件合并压缩
RequireJS的define 以及require 对于我们进行简化JavaScript 开发,进行模块化的处理具有很大的帮助 但是请求加载的js 文件会有一些影响,一般的处理是对于文件进行压缩,但 ...
- uglifyjs 合并压缩 js, clean-css 合并压缩css
本文主要介绍如何通过CLI命令行(也就是终端或者cmd打开的那个shell窗口)实现 js和 css 的合并压缩. uglifyjs 合并压缩 js: 1.安装node 这一步就不多说了,下载node ...
随机推荐
- CoreCLR 在 Linux 下编译成功
https://github.com/dotnet/coreclr/wiki/Building-and-Running-CoreCLR-on-Linux ubuntu-14.10 clang --ve ...
- 【菜鸟玩Linux开发】在Linux中使用VS Code编译调试C++项目
最近项目需求,需要在Linux下开发C++相关项目,经过一番摸索,简单总结了一下如何通过VS Code进行编译调试的一些注意事项. 关于VS Code在Linux下的安装这里就不提了,不管是CentO ...
- [转]C#调用FFMPEG,并异步读取输出信息的代码
http://www.cnblogs.com/Leo_wl/archive/2011/12/31/2308841.html
- 可在广域网部署运行的QQ高仿版 -- GG叽叽V3.4,增加系统设置、最近联系人、群功能(源码)
自从上次版本(GG叽叽V3.2,增加离线消息.离线文件功能)发布后,我个人觉得主要的大功能都实现得差不多了,接下来的几个版本将不断优化GG的细节,提高其可用性.这次版本更新的内容主要是为GG增加了系统 ...
- Unsafe与CAS
Unsafe 简单讲一下这个类.Java无法直接访问底层操作系统,而是通过本地(native)方法来访问.不过尽管如此,JVM还是开了一个后门,JDK中有一个类Unsafe,它提供了硬件级别的原子操作 ...
- DOM何时Ready
由于script标签在被加载完成后会立即执行其中代码,如果在代码中要访问HTMLElement,可是这时候元素还没有加载进来,所以对元素的操作统统无效. 最早的时候使用window.onload = ...
- 冲刺阶段day7
day7 项目进展 又是一个周三,有轮到我写东西了.首先我们对昨天的成果调试了几遍,改了几个小Bug之后就没有什么问题了,完善了登录界面的代码,学生管理这部分终于被敲定下来,并且正式完工了.然后还生下 ...
- 手把手教你用python打造网易公开课视频下载软件2-编码相关说明
函数getdownLoadInfo(url)主要实现核心功能:根据url地址,获取课程信息:课程名(courseTitle),课程数目(courseCount),可下载视频数目(videoCount) ...
- js模版引擎handlebars.js实用教程——each嵌套
<!DOCTYPE html> <html> <head> <META http-equiv=Content-Type content="text/ ...
- Hibernate inverse用法(转载)
出处:http://blog.csdn.net/xiaoxian8023/article/details/15380529 一.Inverse是hibernate双向关系中的基本概念.inverse的 ...