首页 > 编程 > .NET > 正文

Asp.net程序优化js、css实现合并与压缩的方法

2024-07-10 12:48:17
字体:
来源:转载
供稿:网友

本文实例讲述了Asp.net程序优化js、css实现合并与压缩的方法。。具体实现方法如下:

访问时将js和css压缩并且缓存在客户端,
采用的是Yahoo.Yui.Compressor组件来完成的,用户可以点击此处本站下载。

创建一个IHttpHandler来处理文件

代码如下:
public class CombineFiles : IHttpHandler
{
        private const string CacheKeyFormat = "_CacheKey_{0}_";

        private const bool IsCompress = true; //需要压缩

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        public void ProcessRequest(HttpContext context)
        {
            HttpRequest request = context.Request;
            HttpResponse response = context.Response;

            string cachekey = string.Empty;

            string type = request.QueryString["type"];
            if (!string.IsNullOrEmpty(type) && (type == "css" || type == "js"))
            {
                if (type == "js")
                {
                    response.ContentType = "text/javascript";

                }
                else if (type == "css")
                {
                    response.ContentType = "text/css";
                }

                cachekey = string.Format(CacheKeyFormat, type);

                CompressCacheItem cacheItem = HttpRuntime.Cache[cachekey] as CompressCacheItem;

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表