상세 컨텐츠

본문 제목

Javascript 자바스크립트, html5 코드 압축, JS 압축 관련

WEB/html5

by AlrepondTech 2020. 9. 20. 07:59

본문

반응형

 

=================================

=================================

=================================

 

 

 

출처: http://jace.tistory.com/category/Javascript

 

1. JavaScript 최적화 도구

2. CSS 최적화 도구

3. 웹 사이트 성능 개선

 

 

Google

홈페이지 : http://code.google.com/p/closure-compiler/

데모 : http://closure-compiler.appspot.com/home

 

 

CompressorRater

홈페이지 : http://compressorrater.thruhere.net/

 

 

 

Fmarcia

데모 : http://fmarcia.info/jsmin/test.html

 

 

 

=================================

=================================

=================================

 

 

출처: http://blog.outsider.ne.kr/269

 

 

웹개발을 하는데 있어 성능에서 중요한 요소중 하나는 용량을 줄이는 것이다. 전송해야할 파일의 용량이 줄어들면 사용자입장에서는 더 빠르게 로딩할 수 있고 서버측에서는 트래픽이 줄어들기 때문에 많은 이점을 가질 수 있다. 그래서 자바스크립트 코드를 압축해서 js파일의 용량을 줄이는걸 도와주는 툴들이 있다. 이번에Ajaxian에서 YUI Compressor Online가 나왔다는 기사가 떴길래 겸사겸사해서 정리해서 올린다.

자바스크립트 압축(Minification)이란 것은 보통 자바스크립트 코딩을 할 때 가독성을 위해서 들여쓰기등 공백이 많이 들어가게 되어 있는데 이런 것을 없애고 코드를 다닥다닥 붙혀서 크기를 줄여주는 것이다. 압축은 말그대로 크기를 줄여주는 것이고암호화(obfuscation)라는 것도 있는데 이것은 변수나 함수명을 이상하게 바꾸어서 코드를 읽기 어렵게 만든다. 당연히 둘다 함께 할수도 있다.

하지만 암호화의 경우는 자바스크립트의 특성상 약각 읽기만 어렵게 만들어 놓은것 뿐이고 해독툴들을 써서 다시 어느정도 보기좋게 할 수도 있기 때문에 결과적으로 암호화라는 큰 의미는 없다. "웹사이트 최적화 기법"을 보면 사이즈면에서 압호화의 효과는 미비하기 때문에 별로 추천하고 있지 않고 있는데 선택은 각자 나름이고 혹 관심이 있다면 YUI의 글을 참고바란다.

내가 아는 것으로는 3가지 서비스가 있다.




JSMIN

JSMIN부터 보자. 자바스크립트계의 요다라고도 불리는 JSON을 창시한 더글라스 크록포드(Douglas Crockford)가 만든 JavaScript Minifier이다. 

 

 

 

 


JSMIN은 JS파일을 압축하는 기능을 가지고 있는 간단한 프로그램(?)형태로 제공되고 있다. 위에 보는다와 같이 사이트에서 다양한 언어로 제공되고 있기 때문에 취향에 따라서 가져다가 사용할 수 있다. 일반적인 윈도우 환경에서는 MS-DOS.exe형태로 배포되는 JSMIN을 가져다가 사용하면 된다. 

 

 


JSMIN.EXE를 받아서 js파일이 있는 곳에 놓고는 위와같이 실행하면 된다.  명령어는

jsmin <압축할파일> 새로만들 파일명 "주석"


와 같은 형태로 사용하면 된다. 뒤에 주석부분을 적지 않아도 되고 적을 경우는 새로만들 js파일 최상단에 주석에 넣은 부분이 주석형태로 추가된다. 

 

 

?

/*********** before Minification **************/
var checker = false; // 체커


function test() {
    alert(checker);
}


test(); // 실행


/*********** after Minification **************/
var checker=false;function test(){alert(checker);}
test();


JSMIN으로 prototype.js를 압축한 모습이다. 보는바와 같이 주석과 공백등은 모두 없애고 특정단위별로 한줄씩 적어주어 용량을 줄여주고 있다.




/packer/

Dean Edwards가 만든 자바스크립트 압축기 packer이다. 

 


웹상에서 간단하게 사용할 수 있다는게 큰 장점이고 옵션으로 Base62 압호화와 변수이름 축소(Shrink variables)를 적용할 수 있다.

?

/*********** before Minification **************/
var checker = false; // 체커


function test() {
   alert(checker);
}


test(); // 실행


/*********** after Minification **************/
var checker=false;function test(){alert(checker)}test();


/*********** after Minification : Base62 encode **************/
eval(function(p,a,c,k,e,r){e=String;if(!''.replace(/^/,String)){while(c--)r[c]=k[c]||c;k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('2 0=3;4 1(){5(0)}1();',6,6,'checker|test|var|false|function|alert'.split('|'),0,{}))


/*********** after Minification : Shrink variables **************/
var checker=false;function test(){alert(checker)}test();


예제소스가 짧아서 Shrink variables가 차이가 없게 나타나버렸다  ㅡ..ㅡ 암호화는 코드읽는 능력이 좋아서 읽을수 있다면 어쩔수 없지만 저 간단한 코드를 도저희 머하겠다는 건지 모를 코드로 만들어 놓았다. 하지만 딘에드워즈가 친절하게unpacker도 만들어주었고 변수이름까지 고대로 잘 디코딩 된다는거~~




YUI Compressor

Yahoo User Interface Library에서 제공하는 YUI Compressor이다. jar파일 형태로 제공되고 있고 사용하려면 자바 1.4이상이 필요하다. 그냥 사용하기는 좀 불편한것 같고(사용까진 안해봤다.) 이걸 이용해서 만든 서비스들이 있다.

 


이 포스팅의 계기를 만들어 준 Rodolphe STOCLIN가 만든 YUI Compressor Online이다. 깔끔한 인터페이스에 얼마나 압축이 되었는지도 시각적으로 표시해 준다. 

?

/*********** before Minification **************/
var checker = false; // 체커


function test() {
   alert(checker);
}


test(); // 실행


/*********** after Minification **************/
var checker=false;function test(){alert(checker)}test();


/*********** after Minification : Minify only, do not obfuscate **************/
var checker=false;function test(){alert(checker)}test();


/*********** after Minification : Preserve all semicolons **************/
var checker=false;function test(){alert(checker)}test();


/*********** after Minification : Disable all micro optimizations **************/
var checker=false;function test(){alert(checker)}test();



먼 차이냐 ㅡ..ㅡ 소스가 간단해서 그런가... 어쨌든 이녀석은 약간 문제가 있다. 한글이 들어갈 경우는 EUC-KR이든 UTF-8이든 한글이 모두 ?로 깨져버린다. 코드에 한글이 들어가 있으면 사용못한다는 얘기다. 

 


Online JavaScript/CSS Compression Using YUI Compressor는 디자인이 평이해서 그렇지 완성도가 더 좋은편이다. 웹상에서 직접 압축하는 것과 파일로 하는 것을 모두 지원하면 js뿐만아니라 CSS의 압축까지도 지원하고 있다. 압축후에는 용량이 어떻게 어떻게 달라졌고 몇퍼센트가 달라졌는지 표시해 주고 있다. 

?

/*********** before Minification **************/
var checker = false; // 체커


function test() {
   alert(checker);
}


test(); // 실행


/*********** after Minification **************/
var checker=false;function test(){alert(checker)}test();


/*********** after Minification : Minify only, do not obfuscate **************/
var checker=false;function test(){alert(checker)}test();


/*********** after Minification : Preserve unnecessary semicolons **************/
var checker=false;function test(){alert(checker);}test();


/*********** after Minification : Disable all the built-in micro optimizations  **************/
var checker=false;function test(){alert(checker)}test();


여기서는 Preserve all semicolons 옵션이 적용되는군....




한꺼번에 툴을 여러개 소개하다보니 포스팅이 좀 길어지긴 했는데 얼마나 줄어드나 보자. 테스트는 2가지 파일로 했다. 소스를 작성하는 형태가 각자 다르기 때문에 압축률에서도 상황에 따라 달라질것으로 생각한다. 내가 최근 프로젝트에서 만들고 있는 49KB짜리 script.js랑 보편화된 127KB짜리 prototype.js를 가지고 테스트 했다.

JSMIN

script.js -> 36KB
prototype.js -> 94KB

/packer/

script.js -> 36KB
script.js -> 22KB (Base62 encode)
script.js -> 32KB (Shrink variables)
prototype.js -> 93KB
prototype.js -> 51KB (Base62 encode)
prototype.js -> 76KB (Shrink variables)

YUI Compressor Online

script.js -> 33KB
script.js -> 35KB (Minify only, do not obfuscate)
script.js -> 35KB (Preserve all semicolons)
script.js -> 35KB (Disable all micro optimizations)
prototype.js -> 74KB
prototype.js -> 93KB (Minify only, do not obfuscate)
prototype.js -> 94KB (Preserve all semicolons)
prototype.js -> 94KB (Disable all micro optimizations)

Online JavaScript/CSS Compression Using YUI Compressor

script.js -> 34KB
script.js -> 36KB (Minify only, do not obfuscate)
script.js -> 34KB (Preserve unnecessary semicolons)
script.js -> 34KB (Disable all the built-in micro optimizations)
prototype.js -> 75KB
prototype.js -> 94KB (Minify only, do not obfuscate)
prototype.js -> 75KB (Preserve unnecessary semicolons)
prototype.js -> 75KB (Disable all the built-in micro optimizations)



다양하게 테스트한건 아니라서 절대성능비교라고 하기는 좀 그렇고 그냥 참고용이다. 

압축화할때는 조심해야 할게 있다. 보면 약간 걱정되는 것처럼 이게 돌아갈까? 하는 생각인데 생각대로 이건 조심해야 된다. 공백이 없어지는 바람에 소스가 달라붙어서 의도하지 않은 오류가 나지 않아야 한다. 이건 충분히 일어날 수 있는 일이기 때문에 평소 코딩습관을 잘 들이는게 좋다고 생각한다. 더글라스 크록포드는 이런 자바스크립트 검증을 위해서 Javascript Varifier인 JSLint를 제공하고 있다.

압축을 하고 난 다음에는 솔직히 유지보수를 할수 없는 지경이기 때문에 개발소스는 그대로 유지하고 배포할때 압축하는 게 맞는 방법인것 같다. 그래서 다들 Java파일 같은 라이브러리로 쓸수 있는 형태로 제공하는 것으로 보인다. 

 

 

=================================

=================================

=================================

 

 

 

출처: http://mizaralcor.tistory.com/15

 

 

※ HTML, JavaScript, CSS 코드 압축 

    : 웹페이지의 빠른 로딩 속도를 위해 압축된 자바 스크립트 코드로 변환 (beautify 코드 -> minify 코드)

 

 

1. Online YUI Compressor

  - 설명

     ① 종류: JS(최적화), CSS(최적화), HTML(가능)

     ② 옵션: 다양(텍스트, 파일, 주소 선택 가능)

     ③ 로딩: 보통

     ④ 특징: 가장 많이 사용

  - 링크: http://www.refresh-sf.com/yui

  - 미리보기

    

 

 

2. CSS Compressor

  - 설명

     ① 종류: CSS(최적화), HTML(가능), JS(가능)

     ② 옵션: 심플

     ③ 로딩: 빠름

  - 링크: http://www.csscompressor.com

  - 미리보기

    

 

 

3. Javascript Compressor

  - 설명

     ① 종류: JS(최적화), CSS(가능), HTML(가능)

     ② 옵션: 심플

     ③ 로딩: 빠름

  - 링크: http://javascriptcompressor.com

  - 미리보기

    

 

 

 

 

반응형

 

728x90

 

 

 

=================================

=================================

=================================

 

 

출처: http://egloos.zum.com/jaures/v/2369570

 

 

퍼포먼스 향상 기법중에 하나가 바로 css 또는 js 파일들을 압축(minify)하는 것이다. 사실 말이 압축이지 실제로 하는 것은 공백 및 주석제거, 파라미터명 축소 등의 기법을 사용해 파일의 용량을 줄여주는 것이다. (Minifier에 따라서 수행되는 작업은 조금씩 다르다.)

이게 왜 중요하냐면, 

function showMsg(userName, messageString) {
 ...
}

위와 같은 function이 있을경우에, 브라우저가 저 function을 실행하는 경우에는 사실 다음과 같은 코드여도 아무런 상관이 없다.


function showMsg(A,B){...}

 

 

그렇다고 처음부터 위와 같은 방식으로 코딩을 하게되면, 각 파라미터의 의미를 이해하기도 어려울 뿐더러 읽기에도 어렵다. 따라서, 개발시에는 기존 방식대로 개발을 하고 서비스 되는 코드에 대해서만 압축 처리를 하는 것이 좋다.

현재 JavaScript 압축툴은 다양한데, 대표적인 것들로는 다음이 있다.


- JSMin : http://crockford.com/javascript/jsmin
- ShrinkSafe : http://dojotoolkit.org/docs/shrinksafe
- packer : http://dean.edwards.name/packer/
- YUI Compressor : http://www.julienlecomte.net/yuicompressor/


하지만 매번 개발하고 난 후, 압축하고 실서비스에 코드를 올리고 하는 작업은 번거로울 수밖에 없다. 따라서 실서비스 배포전에 압축 자동화를 통해 이와 같은 번거로움을 피하도록 해보자.

압축툴은 경험상 YUI Compressor가 제일 무난한듯 하다. JS 파일뿐만 아니라 CSS 파일까지도 지원하기 때문에 압축 대상이 다른툴에 비해 조금은 더 넓다.

YUI Compressor는 jar 파일로 되어 있어서, JVM이 설치된 곳이라면 command line으로 실행할 수 있다.

다음과 같은 구조를 갖는 프로젝트를 예로 살펴보기로 하자.

 


우선 Ant build.xml에 다음과 같은 target을 만든다.

 <target name="js.minify" description="JS 파일 minify 처리">
  <echo># JS 디렉토리 구조 복사 및 기존 Minified 파일 삭제 ...</echo>
  <copy todir="${js.dir}/minify" overwrite="true" includeemptydirs="true">
   <fileset dir="${js.dir}" excludes="**/.svn/, **/minify/, **/*.js" />
  </copy>
  <delete>
   <fileset dir="${js.dir}/minify" includes="**/*.js" />
  </delete>

  <echo># JS 파일 Minifying ...</echo>  
  <apply executable="java" parallel="false">
         <fileset dir="${js.dir}" includes="**/*.js" />
         <arg line="-jar" />
         <arg path="${basedir}/yuicompressor.jar" />
   <srcfile />
      <arg line="--charset UTF-8 --type js -o" />
   <mapper type="glob" from="*.js" to="${js.dir}/minify/*.js" />
   <targetfile />
  </apply>
 </target>

 
JS 폴더내에 minify 라는 서브 폴더를 생성한다. 그리고 이전 압축 작업의 파일들이 남아 있을 수 있기 때문에 *.js 파일을 삭제한 후, YUI Compressor에 필요한 파라미터 옵션을 주어 압축을 실행한다.

혹시라도 캐릭터셋이 위와 같이 UTF-8이 아닌 다른 파일들을 처리해야 하는 경우에는, <fileset dir="${js.dir}" includes="**/*.js" excludes="불포함 파일" /> 에 excludes로 UTF-8이 아닌 파일들의 목록을 지정하고, apply 항목을 새로 추가해 chatset을 새롭게 지정해 처리하면 된다.

실행은 간단하다. build.xml 파일 위에서 마우스 오른쪽 버튼을 눌러 메뉴에서 Run As > Ant Build... 를 선택한 후, 해당 target을 선택하고 Run 하면 끝이다.

 

 

 

실행 후에 각 폴더를 살펴보면 minify 폴더 아래에 압축된 파일이 생성되어 있음을 확인할 수 있다.

 

다음은 완성된 build.xml 파일이다.

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

 <project name="java_test" default="clean" basedir=".." >
 <property name="WebRoot.dir" value="${basedir}/webapp" />
 <property name="css.dir" value="${WebRoot.dir}/css" />
 <property name="js.dir" value="${WebRoot.dir}/javascript" />

 <target name="css.minify" description="CSS 파일 minify 처리">
  <echo># CSS 디렉토리 구조 복사 및 기존 Minified 파일 삭제 ...</echo>
  <copy todir="${css.dir}/minify" overwrite="true" includeemptydirs="true">
   <fileset dir="${css.dir}" excludes="**/.svn/, **/minify/, **/*.css" />
  </copy>
  <delete>
   <fileset dir="${css.dir}/minify" includes="**/*.css" />
  </delete>

  <echo># CSS 파일 Minifying ...</echo>
  <apply executable="java" parallel="false">
         <fileset dir="${css.dir}" includes="**/*.css" excludes="**/.svn/, **/minify/" />
         <arg line="-jar" />
         <arg path="${basedir}/yuicompressor.jar" />
   <srcfile />
      <arg line="--charset UTF-8 -o" />
   <mapper type="glob" from="*.css" to="${css.dir}/minify/*.css" />
   <targetfile />
  </apply>
 </target>

 <target name="js.minify" description="JS 파일 minify 처리">
  <echo># JS 디렉토리 구조 복사 및 기존 Minified 파일 삭제 ...</echo>
  <copy todir="${js.dir}/minify" overwrite="true" includeemptydirs="true">
   <fileset dir="${js.dir}" excludes="**/.svn/, **/minify/, **/*.js" />
  </copy>
  <delete>
   <fileset dir="${js.dir}/minify" includes="**/*.js" />
  </delete>

  <echo># JS 파일 Minifying ...</echo>  
  <apply executable="java" parallel="false">
         <fileset dir="${js.dir}" includes="**/*.js" />
         <arg line="-jar" />
         <arg path="${basedir}/yuicompressor.jar" />
   <srcfile />
      <arg line="--charset UTF-8 --type js -o" />
   <mapper type="glob" from="*.js" to="${js.dir}/minify/*.js" />
   <targetfile />
  </apply>
 </target>

</project>

Ant를 이용하면, 이처럼 간단하게 서버 배포 작업시에 CSS와 JS 파일이 압축되어 배포되도록 구성할 수 있기 때문에 자동화 환경을 구축할 수 있다.

참고로 압축된 파일만 실서비스에 배포되는 경우에는 아주 급한 상황발생 시, 서버에서 직접 수정이 필요한 경우에는 압축되어 있는 파일을 수정하기가 매우 어렵다. 따라서 혹시 발생할 수도 있는 경우를 대비해 압축되지 않은 파일도 서버의 적당한 곳에 배포하는 것이 좋다.

 

 

=================================

=================================

=================================

 

 

출처: http://chirow.tistory.com/330

 

2차 출처: ref.> http://betterexplained.com/articles/how-to-optimize-your-site-with-gzip-compression/

 

 

How To Optimize Your Site With GZIP Compression

Compression is a simple, effective way to save bandwidth and speed up your site. I hesitated when recommending gzip compression when speeding up your javascriptbecause of problems in older browsers.

But it's the 21st century. Most of my traffic comes from modern browsers, and quite frankly, most of my users are fairly tech-savvy. I don't want to slow everyone else down because somebody is chugging along on IE 4.0 on Windows 95. Google and Yahoo use gzip compression. A modern browser is needed to enjoy modern web content and modern web speed -- so gzip encoding it is. Here's how to set it up.

Wait, wait, wait: Why are we doing this?

Before we start I should explain what content encoding is. When you request a file likehttp://www.yahoo.com/index.html, your browser talks to a web server. The conversation goes a little like this:

 

 

1. Browser: Hey, GET me /index.html
2. Server: Ok, let me see if index.html is lying around...
3. Server: Found it! Here's your response code (200 OK) and I'm sending the file.
4. Browser: 100KB? Ouch... waiting, waiting... ok, it's loaded.

Of course, the actual headers and protocols are much more formal (monitor them withLive HTTP Headers if you're so inclined).

But it worked, and you got your file.

So what's the problem?

Well, the system works, but it's not that efficient. 100KB is a lot of text, and frankly,HTML is redundant. Every <html>, <table> and <div> tag has a closing tag that's almost the same. Words are repeated throughout the document. Any way you slice it,HTML (and its beefy cousin, XML) is not lean.

And what's the plan when a file's too big? Zip it!

If we could send a .zip file to the browser (index.html.zip) instead of plain old index.html, we'd save on bandwidth and download time. The browser could download the zipped file, extract it, and then show it to user, who's in a good mood because the page loaded quickly. The browser-server conversation might look like this:

 

 

1. Browser: Hey, can I GET index.html? I'll take a compressed version if you've got it.
2. Server: Let me find the file... yep, it's here. And you'll take a compressed version? Awesome.
3. Server: Ok, I've found index.html (200 OK), am zipping it and sending it over.
4. Browser: Great! It's only 10KB. I'll unzip it and show the user.

The formula is simple: Smaller file = faster download = happy user.

Don't believe me? The HTML portion of the yahoo home page goes from 101kb to 15kb after compression:

 

 

The (not so) hairy details

The tricky part of this exchange is the browser and server knowing it's ok to send a zipped file over. The agreement has two parts

  • The browser sends a header telling the server it accepts compressed content (gzip and deflate are two compression schemes): Accept-Encoding: gzip, deflate
  • The server sends a response if the content is actually compressed: Content-Encoding: gzip

If the server doesn't send the content-encoding response header, it means the file is not compressed (the default on many servers). The "Accept-encoding" header is just a request by the browser, not a demand. If the server doesn't want to send back compressed content, the browser has to make do with the heavy regular version.

Setting up the server

The "good news" is that we can't control the browser. It either sends the Accept-encoding: gzip, deflate header or it doesn't.

Our job is to configure the server so it returns zipped content if the browser can handle it, saving bandwidth for everyone (and giving us a happy user).

For IIS, enable compression in the settings.

In Apache, enabling output compression is fairly straightforward. Add the following to your .htaccess file:

# compress text, html, javascript, css, xml: AddOutputFilterByType DEFLATE text/plain AddOutputFilterByType DEFLATE text/html AddOutputFilterByType DEFLATE text/xml AddOutputFilterByType DEFLATE text/css AddOutputFilterByType DEFLATE application/xml AddOutputFilterByType DEFLATE application/xhtml+xml AddOutputFilterByType DEFLATE application/rss+xml AddOutputFilterByType DEFLATE application/javascript AddOutputFilterByType DEFLATE application/x-javascript # Or, compress certain file types by extension: <files *.html> SetOutputFilter DEFLATE </files>

Apache actually has two compression options:

  • mod_deflate is easier to set up and is standard.
  • mod_gzip seems more powerful: you can pre-compress content.

Deflate is quick and works, so I use it; use mod_gzip if that floats your boat. In either case, Apache checks if the browser sent the "Accept-encoding" header and returns the compressed or regular version of the file. However, some older browsers may have trouble (more below) and there are special directives you can add to correct this.

If you can't change your .htaccess file, you can use PHP to return compressed content. Give your HTML file a .php extension and add this code to the top:

In PHP:

<?php if (substr_count($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip')) ob_start("ob_gzhandler"); else ob_start(); ?>

We check the "Accept-encoding" header and return a gzipped version of the file (otherwise the regular version). This is almost like building your own webserver (what fun!). But really, try to use Apache to compress your output if you can help it. You don't want to monkey with your files.

Verify Your Compression

Once you've configured your server, check to make sure you're actually serving up compressed content.

  • Online: Use the online gzip test to check whether your page is compressed.
  • In your browser: Use Web Developer Toolbar > Information > View Document Size (like I did for Yahoo, above) to see whether the page is compressed.
  • View the headers: Use Live HTTP Headers to examine the response. Look for a line that says "Content-encoding: gzip".

Be prepared to marvel at the results. The instacalc homepage shrunk from 36k to 10k, a 75% reduction in size.

Try Some Examples

I've set up some pages and a downloadable example:

  • index.html - No explicit compression (on this server, I am using compression by default  ).
  • index.htm - Explicitly compressed with Apache .htaccess using *.htm as a rule
  • index.php - Explicitly compressed using the PHP header

Feel free to download the files, put them on your server and tweak the settings.

Caveats

As exciting as it may appear, HTTP Compression isn't all fun and games. Here's what to watch out for:

  • Older browsers: Yes, some browsers still may have trouble with compressed content (they say they can accept it, but really they can't). If your site absolutely must work with Netscape 1.0 on Windows 95, you may not want to use HTTPCompression. Apache mod_deflate has some rules to avoid compression for older browsers.
  • Already-compressed content: Most images, music and videos are already compressed. Don't waste time compressing them again. In fact, you probably only need to compress the "big 3" (HTML, CSS and Javascript).
  • CPU-load: Compressing content on-the-fly uses CPU time and saves bandwidth. Usually this is a great tradeoff given the speed of compression. There are ways to pre-compress static content and send over the compressed versions. This requires more configuration; even if it's not possible, compressing output may still be a net win. Using CPU cycles for a faster user experience is well worth it, given the short attention spans on the web.

Enabling compression is one of the fastest ways to improve your site's performance. Go forth, set it up, and let your users enjoy the benefits.

Other Posts In This Series

  1. How To Optimize Your Site With HTTP Caching
  2. How To Optimize Your Site With GZIP Compression (This post)
  3. How To Debug Web Applications With Firefox
  4. Speed Up Your Javascript Load Time
  5. Speed Up Your Javascript, Part 2: Downloadable Examples!

 

 

=================================

=================================

=================================

 

 

출처: http://pat.im/657

 

 

  HTML에 들어가는 외부 CSS(Cascading Style Sheet) 및 자바스크립트(JAVAScript, 약칭 JS)는 수가 많고 용량이 클수록 문서가 늦게 뜨는 원인이 된다. 그러므로 누리집(사이트)이 조금이라도 빠르게 뜨게 하려면 이들을 통합하고 압축하여 전송량(트래픽)을 줄여야 좋다.

  JSMinYUI CompressorCreativyst® CSS & JavaScript Compressor 등은 문법이 어긋나지 않는 범위에서 아래와 같이 CSS와 JS의 쓸모 없는 문자를 없앤다.

@charset "utf-8";
* {
margin: 0;
padding: 0;
}

html {
background-color: #a8a8a8;
}

body {
background: url('./images/bg_bodyTop.gif') 50% top repeat-x;
color: #666;
font: 1.2em/1.7 Helvetica, AppleGothic, Gulim, '굴림', sans-serif;
font-size: 75%;
padding-top: 30px;
}

@charset "utf-8";*{margin:0;padding:0}html{background-color:#a8a8a8}body{background:url('/images/bg_bodyTop.gif') 50% top repeat-x;color:#666;font:1.2em/1.7 Helvetica,AppleGothic,Gulim,'굴림',sans-serif;font-size:75%;padding-top:30px}

  또다른 방법으로 GZip 압축이 있다. CSS와 JS는 글(텍스트) 위주여서 GZip 압축만으로도 70~80%에 이르는 전송량을 줄일 수 있다. 두 방식을 함께 쓰면 차이는 크지 않더라도 전송량을 좀 더 줄일 수 있다.

  두 압축 방식 모두 원본을 가공하는 과정을 거치므로, 자주 갱신되는 파일은 수동으로 관리하기가 보통 일이 아니다. 누리집의 규모가 크고 작음을 떠나 자동 도구의 도움을 받는 편이 여러 모로 편리하다.

  워드프레스에서는 JS/CSS를 GZip로 압축전송하는 도구로 WP Super Cache를 꼽을 수 있다. XpressEngine(제로보드 XE)은 내부에서 쓰는 CSS, JS를 자체에서 ?.css.php와 ?.js.php로 묶어 GZip로 전송하는데, 다른 외부 파일은 그대로 전송한다.

  반면에 텍스트큐브는 이런 기능이 아예 없다. 도아님의 압축전송 플러그인으로 HTML은 압축할 수 있지만, CSS와 JS는 압축하지 못한다. 텍스트큐브는 다른 블로그 틀보다 기본 전송량이 많아서 압축전송 기능이 없는 게 매우 아쉬웠다.

  다행히 누리집 또는 블로그 틀에 얽매이지 않고 계정에 설치해 쓰는 압축전송 도구들이 몇 있다. 여기에서 소개할 Minify는 JSMin 등 여러 압축기를 내장하고, GZip 압축전송도 지원한다. Minify는 압축전송에 관한 종합판이라 해야 할 만큼 부가 기능을 많이 담고 있다.

 

Minify 설치

  Minify는 mod_rewrite와 PHP 5.2.1 이상을 지원하는 웹 서버 환경에서 쓸 수 있다.(PHP 4를 지원하는 판은 따로 있다.) .htaccess 파일과 Minify 안에 포함된 config.php 파일을 조금 손보아야  한다.

   먼저 http://code.google.com/p/minify에서 ZIP 형식으로 묶인 Minify를 받는다. 파일 안에는 /min 과 /min_test_units가 들어 있는데, 압축 전송에 필요한 파일은 /min에 있고  /min_test_units은 작동 상황을 시험하기 위한 것이다. 압축을 풀어서 /min을 되도록 누리집의 뿌리 경로(public_html) CSS와 JS의 경로를 좌우하는 .htaccess의 경로 안에 올린다. (.htaccess가 없었다면 뒤 과정에서 만듦)

  그리고 /min/config.php의 매개변수를 손수 고쳐서 올린다.

  Minify는 압축했던 파일을 저장했다가 다시 쓰는 시렁(캐시) 기능이 있다. $min_cachePath에 시렁 경로를 넣으면 기능이 작동한다. 가령 /min/cache를 시렁 경로로 쓰려면, /min/cache를 방을 만들고 다음처럼 값을 넣는다.

$min_cachePath = './cache';

  $min_documentRoot에는 계정 기본 주소의 절대경로를 넣는 곳이다. /min이 public_html의 바로 밑에 올 때는 값을 지정하지 않아도 알아서 처리한다. 서브도메인 정책 등으로 /min이 public_html 바로 밑에 올 수 없을 때는 주석문으로 되어 있는 다음 값으로 바꿔 준다.

$min_documentRoot = substr(__FILE__, 0, strlen(__FILE__) - 15);

  그리고 계정 뿌리 경로  CSS와 JS 경로를 좌우하는 .htaccess에 다음 내용을 끼워 넣는다. 첫 문장은 .htaccess에 이미 들어 있으면 무시해도 된다.

RewriteEngine On
RewriteRule ^(.*\.(css|js))$ /min/index.php?f=$1 [L]

압축전송 확인

  웹에서는 HTTP Compression Test에서 압축 상황을 확인할 수 있다. 아래에 시험한 test.css는 실제 용량이 26.2KB인데, JSMin으로 먼저 처리되어 18.9KB로 줄었다. 오른쪽에서 test2.css는 test.css와 같은 파일이다. Minify는 ~.net/aaa.css,bbb.css처럼 쉼표로 파일들을 열거하면 파일들을 병합하여 전송한다. 내용이 같은 파일을 합쳤으므로 GZip로 압축된 전송량(오른쪽)은 단일 파일을 압축한 전송한 것(왼쪽)과 비슷하다..






단일 CSS 전송





통합 CSS 전송

  파이어폭스(FireFox)에서는 부가 기능으로 설치하는 YSlow로 전송 상황을 확인할 수 있다. (YSlow는 Firebug 안에서 돌아가므로 Firebug를 먼저 설치해야 쓸 수 있다.) 아래는 이 블로그의 전송량을 YSlow로 본 화면이다. SIZE(KB)에 나온 수치는 JSMin으로 먼저 처리된 용량이다. Minify를 막 설치하고 나서는 파이어폭스의 시렁(캐시)에 옛 파일들이 남아서 압축되지 않는 것으로 나올 수 있으므로, 도구→설정→고급→네트워크에서 '오프라인 보관소'를 비우고 확인해야 정확하다.

 

 

YSlow에서 전송량 확인하기




참고한 곳 : Firejune Blog | 자바스크립트 실시간 압축기 - Minify

 

 

=================================

=================================

=================================

 

 

 

 

 

 

 

 

 

반응형


관련글 더보기

댓글 영역