【转载】Yui.Compressor高性能ASP.NET开发:自动压缩CSS、JS

在开发中编写的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

时间: 2024-08-06 17:58:14

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

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

Google Pagespeed,自动压缩优化JS/CSS/Image 浏览:257 发布日期:2015/07/05 分类:技术分享 关键字: Nginx Appache Pagespeed 自动压缩优化JS/CSS/Image 这个周末,把服务器的Nginx升级了下,并加入了Google Pagespeed模块 效果很明显: 页面加载的多个JS.CSS会自动合并压缩处理 发现新版本的Pagespeed能很好的发现处理用户加载的第三方JS库,如jQuery 发现新版本的lazyload_imag

ASP.NET RAZOR自动生成的js Timer

<input type="hidden" value="@(Model.TimeLength)" id="examTimeLength" /> <input type="hidden" value="@ViewData["ExamId"]" id="_ControlerId" /> <span id="@ViewData[&qu

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

很多站点都是用了静态文件分离.我推荐一种处理静态文件分离的方式. BundleExtensions.cs public static class BundleExtensions { public static string Version = "1.0.0"; public static string ScriptsPath = "Cdn"; public static Bundle Production(this Bundle bundle, string cd

关于webStrom-11.1配置less且自动生成.css和自动压缩为.min.css/.min.js

网上看过很多配置思路,自己总结了以下, 就把我个人配置的顺序以及材料分享下,webstrom以下简称WB 1.配置less需要安装nodejs,自行安装.因为要用到npm.我是直接把npm解压到C盘根目录的,先下载解压好待用 npm解压包百度云下载地址:http://pan.baidu.com/s/1bpdnmGZ (yuicompressor-2.4.2.jar 这个是WB配置让CSS或者JS自动生成.mincss/.minjs的压缩工具,不是配置LESS的工具哦, 使用很简单不用解压,比我直

YUI Compressor 压缩 JavaScript 原理-《转载》

YUI Compressor 压缩 JavaScript 的内容包括: 移除注释 移除额外的空格 细微优化 标识符替换(Identifier Replacement) YUI Compressor包括哪些细微优化呢? object["property"] ,如果属性名是合法的 JavaScript 标识符(注:合法的 JavaScript 标识符——由一个字母开头,其后选择性地加上一个或者多个字母.数字或下划线)且不是保留字,将优化为: object.property . {"

Asp.Net使用Yahoo.Yui.Compressor.dll压缩Js|Css

网上压缩css和js工具很多,但在我们的系统中总有特殊的地方.也许你会觉得用第三方的压缩工具很麻烦.我就遇到了这样问题,我不想在本地压缩,只想更新到服务器上去压缩,服务器压缩也不用备份之类的操作.于是我就想着自己实现压缩工具. 初步需求如下: 使用Yahoo.Yui.Compressor 2.0版本 只对网站目录下指定文件夹中css和js进行压缩 使用到了JQuery插件,所以有很多都是压缩过的js.所以对文件名称中保存min的不进行压缩 不需要备份文件 如在第一次访问文件时候进行压缩或应用程序

ASP.Net开发基础温故知新学习笔记

申明:本文是学习2014版ASP.Net视频教程的学习笔记,仅供本人复习之用,也没有发布到博客园首页. 一.一般处理程序基础 (1)表单提交注意点: ①GET通过URL,POST通过报文体: ②需在HTML中为表单元素设置name: ③元素id是给Dom用的,name才是提交给服务器用的: (2)请求处理响应模型: ①浏览器发出访问请求→②服务器处理访问请求并返回HTML→③浏览器解析HTML并显示页面 (3)GET与POST的区别:(★★★→重点) ①GET通过URL传值,而POST通过HTT

C#Css/Js静态文件压缩--Yui.Compressor.Net

一.Asp.Net 自带静态文件压缩工具包 Microsoft.AspNet.Web.Optimization http://www.nuget.org/packages/Microsoft.AspNet.Web.Optimization/1.1.3 但好像没有提供可直接条用的压缩方法,并且再用mvc4.0的时候,同一个网站多个域名也出现了一些问题.于是有了下面 二.使用Yahoo for .Net 的压缩工具,Nuget包名称:YUICompressor.NET Yahoo.Yui.Compr

高性能PHP应用开发-总结

最近将<高性能PHP应用开发>这本书看了两遍,觉得还是受益匪浅的,该书讲的面比较广,都是经验性的内容,建议大家有时间可以详细看一下的,基于此特意将本书的精华易用的部分加以整理,子曰:“温故而知新,可以为师矣.” [第一章  基准测试工具] 一:Apache Benchmark (ab) 随 apache包一起安装ab -n (请求数) -c (并发数,不能起过-n) -t (请求的秒数) http://url 报告中最重要的是以下字段内容:-------------------------HT