Asp.net合并JS,Css文件,只要在路径中添加要压缩的文件名
网上有好提供压缩的组件,但个人感觉比较麻烦,要配置好多东西,还会压缩整个文件夹下面的文件,Php网站提供了一种传参数的方法,在我的以前文件里面有提到过,不过我没有贴出完整的解决方法,今天把代码直接贴出来,供大家参考学习,直接上代码了:
实现原理,利用Urlwriter组件,重定向要压缩的文件,如样例:
script type="text/javascript" src="http://localhost/NhibernateWeb/Js/jquery?v=js/jquery-1.7.2.js,js/validate/jquery.metadata.js"></script>
1、web.config
[html]
<configSections>
<!--设置地址重写组件-->
<section name="rewriter" requirePermission="false" type="Intelligencia.UrlRewriter.Configuration.RewriterConfigurationSectionHandler, Intelligencia.UrlRewriter"></section>
</configSections>
<!--rewriter config-->
<rewriter file="~/App_Data/rewrite.xml"/>
2、重写文件rewrite.xml
[html]
<?xml version="1.0" encoding="utf-8" ?>
<rewriteRules>
<rewrite url="^~/Js/jquery\?v=([0-9a-zA-Z\.,-\/]+)$" to="~/MegerCompress.ashx" />
</rewriteRules>
3、前台文件 MegerJsCss.aspx
[html]
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
<link type="text/css" href="http://localhost/NhibernateWeb/PagecontrolStyle.css" />
<link type="text/css" href="Css/index.css" rel="Stylesheet"/>
<script type="text/javascript" src="http://localhost/NhibernateWeb/Js/jquery?v=js/jquery-1.7.2.js,js/validate/jquery.metadata.js"></script>
<script type="text/javascript">
$(function() {
jQuery.mytest = function() {
alert("ok");
}
})
$(function() {
$.mytest();
})
</script>
</head>
<body>
<form id="form1" runat="server">
<div style="width:100%;height:500px;">
</div>
</form>
</body>
</html>
4、后台处理文件 MegerCompress.ashx
[vb]
Imports System.Web
Imports System.Web.Services
Imports System.Collections.Generic
Imports System.Text
Imports System.IO
Imports Yahoo.Yui.Compressor
Public Class MegerCompress
Implements System.Web.IHttpHandler
Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
context.Response.ContentType = "text/javascript"
'context.Response.Write("function f(){}")
Dim s As String = context.Request("v")
Dim jspath() As String = s.Split(",")
Dim strContent As New StringBuilder
For i As Integer = 0 To jspath.Length - 1
Next
Dim fpath As String = System.Web.HttpContext.Current.Server.MapPath(jspath(0))
If File.Exists(fpath) Then
'读取文本
Dim sr As New StreamReader(fpath, System.Text.Encoding.UTF8)
Dim str As String = sr.ReadToEnd()
sr.Close()
strContent.Append(str)
End If
Dim js As New JavaScriptCompressor(strContent.ToString(), False, Encoding.UTF8, System.Globalization.CultureInfo.CurrentCulture)
context.Response.Write(js.Compress)
End Sub
ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
End Class
个人测试结果分享:
编号 行为 页面大小 时间
1 按文件路径逐个加载 490.7K 500ms(onload2.45s)
2 动态加载(上面) 334.1 1.97s(onload3.73s)
3 用工具压缩成一个文件 334.1 391ms(onload3.07s)
结论上面的方法可以实现动态按需加载,但问题是效率不怎么高,最好是用工具压缩需要的文件,最好加载压缩文件。
补充:Web开发 , ASP.Net ,