개발자의 길

웹 페이지 속도 향상 본문

1. 개발자

웹 페이지 속도 향상

자르르 2010. 8. 25. 15:31


자신이 직접 홈페이지를 만들거나 기존에 만들어진 홈페이지를 웹 브라우저로 접속했을때 시간이 오래 걸리는 경우에 몇가지 방법으로 속도를 향상 시킬수 있습니다.

1. 스타일시트(CSS)와 자바스크립트(JavaScript) 외부화
HTML에 스타일시트와 자바스크립트를 직접적으로 넣어 사용할 경우 웹 페이지 로딩시 다운로드 시간이 필요하게 되므로 전체 페이지의 속도가 느려질수 있습니다. 따라서 스타일시트와 자바스크립트 파일을 사용할 경우에는 반드시 필요한 경우에만 사용하는 것이 좋습니다.

스타일시트, 자바스크립트의 외부화
<link href="css/stylesheets.css" media="all" rel="Stylesheet" type="text/css" />
<script src="js/javascript.js" type="text/javascript"></script>

2. 스타일시트는 위에 자바스크립트는 아래
스타일시트는 <head> 와 </head> 사이에 넣어두고 자바스크립트는 </body> 바로 위쪽에 넣어 두는것이 속도면에서 더욱 좋습니다.
아래 주소는 자바스크립트는 위에 넣었을 때(왼쪽)와 아래 넣었을때(오른쪽)의 차이점을 비교 해줍니다.
http://stevesouders.com/hpws/move-scripts.php

예제1) 스타일시트는 위에 자바스크립트는 아래
<!DOCTYPE html>
<html>
<head>
<title>Hello?</title>
<meta charset="EUC-KR">
<link href="css/style.css" media="all" rel="Stylesheet" type="text/css" />
</head>
<body>
<div id="message">
    <form name="form1">
        <select name="formselect2" size="1" -nChange="namosw_goto_byselect(this, 'blank')">
                   <option selected value="http://www.naver.com/">네이버</option>
                   <option value="http://www.daum.net/">다음</option>
                   <option value="http://www.nate.com/">네이트</option>
                   <option value="http://kr.yahoo.com/">야후</option>
        </select>
    </form>
</div>
<script src="js/javascript.js" type="text/javascript"></script>
</body>
</html>

3. 스타일시트, 자바스크립트 최적화
예를 들어 아래와 같은 스타일이 있다고 치면 보기 쉽게 하기 위해서 공백을 추가 하게 되었습니다.
보기에는 좋으나 공백으로 인한 파일의 크기가 증가 됩니다.
#message {
   position: absolute;
   left: 40em;
   right: 1em;
}
공백 제거를 하게 되면 보기에는 엉망해 보이지만 파일의 크기가 줄어듭니다. 따라서, 공백을 제거시 파일의 크기가 줄어들어 클라이언트 쪽에서 빠르게 다운로드를 할수 있게 된다는 점입니다.
#message{position:absolute;left:40em;right:1em}

공백 제거를 아래의 사이트에서 사용하시면 되겠습니다.
http://www.cssoptimiser.com/

 

자바스크립트의 경우도 아래 압축툴로 해결 볼수 있습니다.(Base62 로 엔코딩하면 압축률이 더 상승 됩니다.)
http://javascriptcompressor.com/

 

4. 테이블, 이미지의 크기 설정
브라우저에서 테이블이나 이미지의 크기를 표시할 방법을 계산하기 위해 많은 연산을 수행하기 때문에 미리 설정 해주면 좋습니다.
<td width="235" height="50">ㅋㅋㅋ</td>
<img src="img/logo.png" width="235" height="50" alt="Logo" />

5. 웹 서버 Cache 및 Gzip 설정
웹 서버를 어떤것으로 사용하느냐에 따라 설정 방법이 틀려지게 되는데.. 보통 많이 사용하는 아파치와 정적 파일이 서빙이 우수한 Nginx 설정 방법을 써보도록 하겠습니다.

- Apache 2.2.x
정적파일(html,css,images...)들에 대한 만료기간(Expires)를 설정 해주면 클라이언트 측에서는 다운로드 후 만료기간까지 재전송 요구를 하지 않기 때문에 동적인 파일이나 페이지등만 다운로드 하게되므로 로딩 속도가 빠르게 됩니다. 단, 클라이언트가 웹브라우저의 최근 방문기록을 삭제하면 재전송을 요구를 할수도 있습니다.
http://httpd.apache.org/docs/2.0/mod/mod_expires.html

아파치에서 expires 를 사용하기 위해서는 mod_expires 모듈이 있어야 하며 httpd.conf 에 모듈을 등록 후 사용하시면 됩니다.
LoadModule expires_module modules/mod_expires.so
# html, css, javascript, images 등과 같은 정적 파일을 1년의 만료기간을 설정합니다.
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType text/html "access plus 1 years"
ExpiresByType text/css "access plus 1 years"
ExpiresByType application/x-javascript "access plus 1 years"
ExpiresByType image/jpeg "access plus 1 years"
ExpiresByType image/gif "access plus 1 years"
ExpiresByType image/png "access plus 1 years"
ExpiresByType image/bmp "access plus 1 years"
ExpiresByType image/cgm "access plus 1 years"
ExpiresByType image/tiff "access plus 1 years"
ExpiresByType video/mpeg "access plus 1 years"
ExpiresByType video/quicktime "access plus 1 years"
ExpiresByType video/x-msvideo "access plus 1 years"
ExpiresByType audio/basic "access plus 1 years"
ExpiresByType audio/midi "access plus 1 years"
ExpiresByType audio/mpeg "access plus 1 years"
ExpiresByType audio/x-aiff "access plus 1 years"
ExpiresByType audio/x-mpegurl "access plus 1 years"
ExpiresByType audio/x-pn-realaudio "access plus 1 years"
ExpiresByType audio/x-wav  "access plus 1 years"
ExpiresByType application/x-shockwave-flash  "access plus 1 years"
</IfModule>

정적파일에 대한 압축 전송을 설정 해주면 파일의 크기가 줄어듭니다.
http://httpd.apache.org/docs/2.0/mod/mod_deflate.html
Gzip 을 사용하기 위해서는 mod_deflate 모듈을 사용하므로 httpd.conf 파일에 아래 내용을 추가 후 사용 하도록 합니다.
LoadModule deflate_module modules/mod_deflate.so
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css text/javascript application/x-javascript
해당 정적파일에 압축을 설정 합니다. 이미지와 음악 및 비디오 등은 이미 압축이 되어 있으므로 설정에서 뺐습니다.

- Nginx
러시아에서 개발한 웹서버이며 정적파일이 우수하고 설치와 설정이 간단하다는 장점이 있습니다. Gzip 과 Expires 를 nginx.conf 에 추가 합니다.
user  nobody;
pid        log/nginx.pid;
error_log  log/error.log;
worker_processes  1;
events {
    worker_connections  1024;
    use kqueue;   # FreeBSD - kqueue
}                       # Linux - epoll
# Syntax: use [ kqueue | rtsig | epoll | /dev/poll | select | poll | eventport ]

http {
    include       mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    '$status $body_bytes_sent "$http_referer" '
    '"$http_user_agent" "$http_x_forwarded_for"';

    access_log   off;

    ## Size Limits
    client_body_buffer_size   1024m;
    client_max_body_size      1024m;
    client_header_buffer_size 1024m;
    large_client_header_buffers 1 1024m;

    ## Timeouts
    send_timeout          5;
    keepalive_timeout     5 5;
    client_body_timeout   5;
    client_header_timeout 5;

    ## General Options
    sendfile                 on;
    server_tokens           off;
    recursive_error_pages    on;
    ignore_invalid_headers   on;
    server_name_in_redirect  off;
    limit_zone gulag $binary_remote_addr 1m;

    ## TCP options 
    tcp_nodelay on;
    tcp_nopush  on;

    ## Expires
    expires       1y;
    add_header    Cache-Control  private;

    ## Compression
    gzip                on;
    gzip_vary         on;
    gzip_static        on;
    gzip_buffers      16 8k;
    gzip_comp_level   9;
    gzip_http_version 1.0;
    gzip_min_length   0;
    gzip_types text/plain image/x-icon text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript;

# Virtualhost
server {
        listen       80;
        server_name  static.yongbok.net;
        root   /home/static/;
        charset utf-8;
    }
}

6. YSlow 로 측정
Yahoo 에서 배포하는 Firefox 플러그인이며 동작을 하기 위해서는 Firebug 가 먼저 설치가 되어 있어야 합니다.
YSlow 는 웹 페이지를 분석후에 Yahoo 에서 제시한 고성능 웹 사이트에 대한 규칙을 참고해( http://developer.yahoo.com/performance/rules.html ) 사용자에게 문제점을 알려줍니다.
YSlow 는 http://developer.yahoo.com/yslow/ 에서 How Do I Get Started? 를 참고하여 순서대로 설치를 하시면 됩니다.

YSlow 를 이용하여 측정 해보면 해당 웹 사이트에 대한 Yahoo 규칙들을 참고하여 점수를 매겨 보여줍니다.
1~5번까지의 과정을 거치면 YSlow 의 점수가 A~C 사이로 보일 가능성이 있습니다.

 

'1. 개발자' 카테고리의 다른 글

이클립스 implementors 파일  (0) 2014.10.30
facebook oauth client 하는 방식 - 단순  (0) 2012.07.03
LevelDB...?  (0) 2011.09.20
soap 통신이란?  (0) 2010.02.26
ping 테스트?  (0) 2010.02.24


이 포스팅은 쿠팡 파트너스 활동의 일환으로, 이에 따른 일정액의 수수료를 제공받습니다.
공유하기 링크
Comments