做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文件合并,压缩,缓存,延迟加载的更多相关文章

  1. gulp 之一 安装及简单CSS,JS文件合并压缩

    最近研究了一下gulp构建工具,发现使用起来比grunt顺手一些.(个人感受),以下是grunt和gulp构建方式和原理: grunt 基于文件方式构建,会把文件先写到临时目录下,然后进行读文件,修改 ...

  2. 使用System.Web.Optimization对CSS和JS文件合并压缩

    在ASP.NET MVC 中JS/CSS文件动态合并及压缩通过调用System.Web.Optimization定义的类ScriptBundle及StyleBundle来实现. 大致步骤如下: 1.A ...

  3. AngularJS结合RequireJS做文件合并压缩的那些坑

    我在项目使用了AngularJS框架,用RequireJS做异步模块加载(AMD),在做文件合并压缩时,遇到了一些坑,有些只是解决了,但不明白原因. 那些坑 1. build.js里面的paths必须 ...

  4. 【JS代码压缩】使用YUI Compressor对js文件进行压缩处理

    概述 在使用html5开发Hybird APP的时候,可能会引入大量的js包,另外对于一些核心的js文件,进行一些特殊的处理, 如压缩和加密就显得很重要了,YUI Compressor就是这样一个用于 ...

  5. 编写gulpfile.js文件:压缩合并css、js

    使用gulp一共有四个步骤: 1. 全局安装 gulp: $ npm install --global gulp 2. 作为项目的开发依赖(devDependencies)安装: $ npm inst ...

  6. 前端js文件合并三种方式

    最近在思考前端js文件该如何合并,当然不包括不能合并文件,而是我们能合并的文件,想了想应该也只有三种方式. 三个方式如下: 1. 一个大文件,所有js合并成一个大文件,所有页面都引用它. 2. 各个页 ...

  7. CSS 和 JS 文件合并工具

    写 CSS 和 JavaScript 的时候, 我们会遇到一个两难的局面: 要么将代码写在一个大文件, 要么将代码分成多个文件. 前者导致文件难以管理, 代码复用性差, 后者则因为需要在载入多个文件令 ...

  8. RequireJS 文件合并压缩

    RequireJS的define 以及require 对于我们进行简化JavaScript 开发,进行模块化的处理具有很大的帮助 但是请求加载的js 文件会有一些影响,一般的处理是对于文件进行压缩,但 ...

  9. uglifyjs 合并压缩 js, clean-css 合并压缩css

    本文主要介绍如何通过CLI命令行(也就是终端或者cmd打开的那个shell窗口)实现 js和 css 的合并压缩. uglifyjs 合并压缩 js: 1.安装node 这一步就不多说了,下载node ...

随机推荐

  1. maven配置发布仓库

    首先,在工程的pom.xml中添加仓库信息 <distributionManagement> <repository> <id>releases</id> ...

  2. AWIT DBackup 0.0.20 发布,备份系统

    AWIT DBackup 0.0.20 修复了几个小 bug. AllWorldIT DBackup 是一个备份系统,为每个目录创建一个独立的压缩包,这更便于搜索. 特点: 使用 xz, bzip2, ...

  3. 微信公共平台开发-(.net实现)3--发送文本消息

    最近,项目这边比较忙,没来得及续写,哎,先吐吐槽吧,在这个周六还得来上班,以后每个周六多要上,一天的滋味真有点受不鸟呀.还不习惯ing... 嗯,别的不说了现在开始接着上次http://www.cnb ...

  4. 用nifi executescript 生成3小时间隔字符串

    import java.io from datetime import datetime from org.apache.commons.io import IOUtils from java.nio ...

  5. Ember.js之动态创建模型

    本人原文地址发布在:点击这里 What problem did we meet? As ember document suggestion, we may define a model as a st ...

  6. ENode 1.0 - Command Service设计思路

    开源地址:https://github.com/tangxuehua/enode 上一篇文章,介绍了enode框架的物理部署思路.本文我们再简单分析一下Command Service的API设计: C ...

  7. 设计模式之美:State(状态)

    索引 意图 结构 参与者 适用性 效果 相关模式 实现 实现方式(一):由 ConcreteState 指定它的后继 State. 意图 允许一个对象在其内部状态改变时改变它的行为.对象看起来似乎修改 ...

  8. jenkins + Git 搭建持续集成环境

    持续集成通过自动化构建.自动化测试以及自动化部署加上较高的集成频率保证了开发系统中的问题能迅速被发现和修复,降低了集成失败的风险,使得系统在开发中始终保持在一个稳定健康的集成状态.jenkins是目前 ...

  9. okhttp教程——起步篇

    okhttp教程--起步篇 这篇文章主要总结Android著名网络框架-okhttp的基础使用,后续可能会有关于他的高级使用. okhttp是什么 okhttp是Android端的一个Http客户端, ...

  10. IOS Animation-动画基础、深入

    1. Model Layer Tree(模型层树)和Presentation Layer Tree(表示层树) CALayer是动画产生的地方.当我们动画添加到Layer时,是不直接修改layer的属 ...