在开发中编写的js、css发布的时候,往往需要进行压缩,以减少文件大小,减轻服务器的负担。这就得每次发版本的时候,对js、js进行压缩,然后再发布。有没有什么办法,让代码到了服务器上边,它自己进行压缩呢?

有两种办法:

第一种,在css、js请求到来的时候读取一下相对应的文件,进行压缩后返回。此方法可以通过在Global.asax的Application_BeginRequest的事件中,进行处理,也可以在web.config中注册一个httpHandler进行处理。

第二种是在程序启动的时候,对全部css以及js进行压缩,压缩之后,每次访问都使用压缩后的文件即可。这种办法可以将js全部压缩到一个文件夹里边,不过需要注意一下文件的顺序。

压缩使用的是雅虎的压缩组件: Yahoo.Yui.Compressor.dll

由于第一种办法没能实现js压缩到一个文件,所以这里采用的是第二种方案。

压缩方法比较简单,首先引用Yahoo.Yui.Compressor.dll和EcmaScript.NET.modified.dll

压缩js

//文件内容

string strContent = File.ReadAllText(jsPath, Encoding.UTF8);

//初始化

var js = new JavaScriptCompressor(strContent, false, Encoding.UTF8, System.Globalization.CultureInfo.CurrentCulture);

//压缩该js

strContent = js.Compress();

File.WriteAllText(jsPath, strContent, Encoding.UTF8);

压缩css

string strContent = File.ReadAllText(cssPath, Encoding.UTF8)

//进行压缩

strContent = CssCompressor.Compress

(strContent);

File.WriteAllText(cssPath, strContent, Encoding.UTF8);

还有另外一一种办法不用自己写代码,每次网站发布的时候自动压缩指定的js和css文件:
1)在项目中新建“MSBuild” 文件夹,把yahoo压缩组件的两个dll放进去
2)在“文件夹”内新建"MSBuildCompressor.xml"文件:

<?xml version="1.0" encoding="utf-8" ?>

<Project xmlns="http://schemas.microsoft.com/developer/MsBuild/2003">

  <UsingTask

  TaskName="CompressorTask"

  AssemblyFile="Yahoo.Yui.Compressor.dll" />

  <!-- The .NET 2.0 version of the task .. and yes .. that's Model.Net20 folder listed twice .. i know i know...

<UsingTask

TaskName="CompressorTask"

        AssemblyFile="..\..\Projects\Yahoo.Yui.Compressor\Model.Net20\Model.Net20\bin\Debug\Yahoo.Yui.Compressor.NET20.dll" />

    -->

  <!-- Define the output locations. These can be set via the msbuild command line using

         /p:CssOutputFile=$(TargetDir)../whatever...

         /p:JavaScriptOutputFile=$(TargetDir)../whatever...

         If they are not supplied or are empty, then we the value whatever is supplied, below.

    -->

  <PropertyGroup>

    <CssOutputFile Condition=" '$(CssOutputFile)'=='' ">

      SylesSheetFinal.css

    </CssOutputFile>

    <JavaScriptOutputFile Condition=" '$(JavaScriptOutputFile)'=='' ">

      JavaScriptFinal.css

    </JavaScriptOutputFile>

  </PropertyGroup>

  <Target Name="MyTaskTarget">

    <!--

ItemGroup\CssFiles or ItemGroup\JavaScriptFiles: add zero to many files you wish to include in this compression task.

                                                             Don't forget, you can use the wildcard (eg. *.css, *.js) if you feel up to it.

                                                             Finally, at least one item is required - either a css file or a js file.

CssFiles/JavaScriptFiles data format: Please do not touch this.

DeleteCssFiles: [Optional] True | Yes | Yeah | Yep | True | FoSho | FoSho. Default is False. Anything else is False. (eg. blah = false, xxxx111 = false, etc)

CssCompressionType: YuiStockCompression | MichaelAshsRegexEnhancements | HaveMyCakeAndEatIt or BestOfBothWorlds or Hybrid; Default is YuiStockCompression.

ObfuscateJavaScript: [Optional] refer to DeleteCssFiles, above.

PreserveAllSemicolons: [Optional] refer to DeleteCssFiles, above.

DisableOptimizations: [Optional] refer to DeleteCssFiles, above.

EncodingType: [Optional] ASCII, BigEndianUnicode, Unicode, UTF32, UTF7, UTF8, Default. Default is 'Default'.

DeleteJavaScriptFiles: [Optional] refer to DeleteCssFiles, above.

LineBreakPosition: [Optional] the position where a line feed is appened when the next semicolon is reached. Default is -1 (never add a line break).
(zero) means add a line break after every semicolon. (This might help with debugging troublesome files). LoggingType: None | ALittleBit | HardcoreBringItOn; Hardcore also lists javascript verbose warnings, if there are any (and there usually is :P ). ThreadCulture: [Optional] the culture you want the thread to run under. Default is 'en-gb'. IsEvalIgnored: [Optional] compress any functions that contain 'eval'. Default is False, which means a function that contains 'eval' will NOT be compressed. It's deemed risky to compress a function containing 'eval'. That said, if the usages are deemed safe this check can be disabled by setting this value to True. --> <ItemGroup> <!-- Single files, listed in order of dependency <CssFiles Include="../StylesheetSample1.css"/> <CssFiles Include="../StylesheetSample2.css"/> <CssFiles Include="../StylesheetSample3.css"/> <CssFiles Include="../StylesheetSample4.css"/>--> <JavaScriptFiles Include="../myjs/sample_1.js"/> <!-- All the files. They will be handled (I assume) in alphabetically. --> <!--<CssFiles Include="*.css" /> <JavaScriptFiles Include="*.js" /> --> </ItemGroup> <CompressorTask CssFiles="@(CssFiles)" DeleteCssFiles="false" CssOutputFile="$(CssOutputFile)" CssCompressionType="YuiStockCompression" JavaScriptFiles="@(JavaScriptFiles)" ObfuscateJavaScript="False" PreserveAllSemicolons="False" DisableOptimizations="Nope" EncodingType="utf-8" DeleteJavaScriptFiles="false" LineBreakPosition="-1" JavaScriptOutputFile="$(JavaScriptOutputFile)" LoggingType="ALittleBit" ThreadCulture="en-au" IsEvalIgnored="false" /> <!-- CssFiles="@(CssFiles)" DeleteCssFiles="false" CssOutputFile="$(CssOutputFile)" CssCompressionType="YuiStockCompression" JavaScriptFiles="@(JavaScriptFiles)" ObfuscateJavaScript="False" //是否模糊处理js文件,True:会将js中的变量为“a,b,c”单个字符的变量 PreserveAllSemicolons="False" DisableOptimizations="Nope" EncodingType="utf-8" //如果js或者css包含有中文,则必须使用utf-8编码,否则会乱码 DeleteJavaScriptFiles="false" LineBreakPosition="-1" JavaScriptOutputFile="$(JavaScriptOutputFile)" LoggingType="ALittleBit" ThreadCulture="en-au" IsEvalIgnored="false" --> </Target> </Project>

3)选择网站属性,切换到“生成事件”标签,,在“”输入以下命令:
$(MSBuildBinPath)\msbuild.exe "$(ProjectDir)MSBuild\MSBuildCompressor.xml" /p:CssOutputFile="../miniFile/Sieena.min.css" /p:JavaScriptOutputFile="../miniFile/Sieena.min.js"

这样,每次编译网站的时候就会自动压缩指定的js和css文件了

实例下载

官方地址:

http://yuicompressor.codeplex.com/wikipage?title=Sample%20MSBuild.xml%20File&ProjectName=yuicompressor

【转载】Yui.Compressor高性能ASP.NET开发:自动压缩CSS、JS的更多相关文章

  1. Google Pagespeed,自动压缩优化JS/CSS/Image

    Google Pagespeed,自动压缩优化JS/CSS/Image 浏览: 发布日期:// 分类:技术分享 关键字: Nginx Appache Pagespeed 自动压缩优化JS/CSS/Im ...

  2. 给YUI Compressor添加右键命令,完成快捷压缩

    YUI Compressor默认不带右键安装功能 YUI Compressor非常好用,特别是JS的混淆是众多JS Coding的最爱.可惜官网提供的版本都不具备右键功能,每次压缩都要cmd输入一些命 ...

  3. JAVA使用YUI压缩CSS/JS

    前言 JS/CSS文件压缩我们经常会用到,可以在网上找在线压缩或者本地直接使用,我这里使用的是yahoo开源组件YUI Compressor.首先介绍一下YUI Compressor,它是一个用来压缩 ...

  4. 使用VS Code开发纸壳CMS自动编译主题压缩CSS,JS

    Visual Studio Code (简称 VS Code / VSC) 是一款免费开源的现代化轻量级代码编辑器,支持语法高亮.智能代码补全.自定义热键.括号匹配.代码片段.代码对比 Diff.GI ...

  5. asp.net mvc自动压缩文件,并生成CDN引用

    很多站点都是用了静态文件分离.我推荐一种处理静态文件分离的方式. BundleExtensions.cs public static class BundleExtensions { public s ...

  6. ASP.NET RAZOR自动生成的js Timer

    <input type="hidden" value="@(Model.TimeLength)" id="examTimeLength" ...

  7. ASP.NET 4.0 Webform Bundles 压缩css, js,为什么放到服务器不行

    参考文章: http://blog.csdn.net/dyllove98/article/details/8758149 文章说的很详细. 但是本地是可以完美展示(我的本地环境有4.0 也有4.5) ...

  8. asp.net mvc项目实记-开启伪静态-Bundle压缩css,js

    百度这些东西,还是会浪费了一些不必要的时间,记录记录以备后续 一.开启伪静态 如果不在web.config中配置管道开关则伪静态无效 首先在RouteConfig.cs中中注册路由 routes.Ma ...

  9. iwebshop 自动给css js链接加版本信息

    lib/core/tag_class.php case 'theme:': $path = $matches[4]; $exts = strtolower(substr($matches[4], st ...

随机推荐

  1. e827. 设置JSplitPane中分隔物的大小

    A divider can be no less than one pixel in size. // Create a left-right split pane JSplitPane pane = ...

  2. ELK+Redis 解析Nginx日志

    一.ELK简介 Elk是指logstash,elasticsearch,kibana三件套,我们一般使用它们做日志分析. ELK工作原理图: 简单来讲ELK具体的工作流程就是客户端的logstash ...

  3. 7款效果惊人的HTML5/CSS3应用

    今天是周末,我为大家收集7个比较经典的HTML5/CSS3应用,每一个都提供源代码,效果非常惊人. 1.CSS3/jQuery创意盒子动画菜单 作为前端开发者,各种各样的jQuery菜单见过不少,这款 ...

  4. Windows 环境搭建Redis集群(win 64位)

    转: http://blog.csdn.net/zsg88/article/details/73715947 参考:https://www.cnblogs.com/tommy-huang/p/6240 ...

  5. 用shell 实现对MySQL数据库分页

    参考链接 http://mp.weixin.qq.com/s?__biz=MzAxMzE4MDI0NQ==&mid=208299533&idx=1&sn=4cab00793eb ...

  6. 监听事件绑定(addEventListener、attachEvent)和移除(removeEventListener、detachEvent)

    /** * @description 事件绑定,兼容各浏览器 * @param target 事件触发对象 * @param type 事件 * @param func 事件处理函数 */ funct ...

  7. Apache+php5

    .下载回来的是解压文件,解压好放到要安装的位置.(我这里以D:\Acpache24为例) .打开Apache24\conf下httpd.conf 文件,用记事本打开即可. ()第37行ServerRo ...

  8. linux环境中安装NRPE插件执行远程"本地资源"检查?NRPE安装?

    需求描述: 在安装完nagios之后,需要对本地资源进行监控,比如磁盘空间的使用,进程数,swap空间,等等.这些都不是通过网络提供出来的, 所以,都是本地资源,可以通过NRPE插件实现在客户端中采集 ...

  9. Hibernate_day01讲义_使用Hibernate完成对CRM系统中客户管理的DAO中的CRUD的操作

  10. Go之类型判断

    boy := util.Boy{util.Person{"Eric", 19, "boy"}, "1"} var boyClone inte ...