做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. 移动app框架inoic功能研究

    原生移动app框架inoic功能研究 本篇只侧重框架提供的功能和能力的研究,请关注后续实际部署使用体验. 一.inoic是什么? inoic是一个可以使用Web技术以hybird方式开发移动app的前 ...

  2. NetMq学习--发布订阅(一)

    基于NeqMq 4.0.0-rc5版本发布端: using (var publisher = new PublisherSocket()) { publisher.Bind("tcp://* ...

  3. ILspy反编译工具

    简介 ILspy是一个开源的.net反编译软件,使用十分方便. 开发原因 之所以开发ILspy是因为Red Gate宣布免费版的.NET Reflector(同样是反编译软件)将会在2011年2月停止 ...

  4. 创建widget

    1. 定义方法 def predictAll(tickers, startdt='36', enddt = 'today', predictdays = 1): if enddt == 'today' ...

  5. 【T-SQL基础】02.联接查询

    概述: 本系列[T-SQL基础]主要是针对T-SQL基础的总结. [T-SQL基础]01.单表查询-几道sql查询题 [T-SQL基础]02.联接查询 [T-SQL基础]03.子查询 [T-SQL基础 ...

  6. 自制Unity小游戏TankHero-2D(1)制作主角坦克

    自制Unity小游戏TankHero-2D(1)制作主角坦克 我在做这样一个坦克游戏,是仿照(http://game.kid.qq.com/a/20140221/028931.htm)这个游戏制作的. ...

  7. HTML5触屏版多线程渲染模板技术分享

    前言: 了解js编译原理的屌丝们都知道,js是单线程的,想当年各路神仙为了实现js的多线程,为了解决innerHTML输出大段HTML卡页面的顽疾,纷纷设计了诸如假冒的“多线程“实现,我自己也在写开源 ...

  8. 让我欲罢不能的node.js

    从我大一接触第一门编程语言C开始,到现在工作三年陆续接触到了C.汇编.C++.C#.Java.JavaScript.PHP,还有一些HTML.CSS神马的,从来没有一门语言让我像对node.js一样的 ...

  9. Visual Studio 2010 实用功能:使用web.config发布文件替换功能

    当建立ASP.NET Web应用程序项目后,默认除了生成web.config外,还生成了web.debug.config与Web.Release.config.顾名思义,根据它们的命名我可以推测到他们 ...

  10. iOS UITableView行高自行扩展

    myTableView.estimatedRowHeight = ; myTableView.rowHeight = UITableViewAutomaticDimension; 不需要实现 - (C ...