SlideShare une entreprise Scribd logo
1  sur  211
Télécharger pour lire hors ligne
1

Mobile Web Application 개발 방법론:
설계, 구현 및 최적화 Guide
임상석 Manager
sangseok.lim@sk.com
SD 개발팀, 플랫폼 기술원
자료 목적
2

대상: 실무 Web App 개발자 및 개발 과제 Project Lead
목적: HTML5를 포함 Web 기술을 기반으로 한 Mobile향 Web
Application 개발시 필요한 SW 설계, 구현 및 최적화 방법에 대한
End-to-End 상세 기술 Guide 제공
Contents
3
¨ 

Mobile Web Application 정의
l 

¨ 

Server-hosted, Hybrid

Mobile Web Application SW Architecture 설계 사례
l 

l 

Audio 기능 개발: Sound Manager2

l 

Fragmentation handling: Modernizr

l 

¨ 

UI/UX 개발: jQuery, jQuery Mobile

Common utilities: touch library, URL bar control

Mobile Web Application Platform Architecture
l 

¨ 

Mobile browser engine architecture

Mobile Web Application End-To-End 성능 최적화 방법론
l 

Front-end단 성능 최적화 guide

l 

From server to client 최적화: profiling tool 및 best practice
HTML5 Mobile Web App 전망
4
SAP's Head of Mobility, Sanjay Poonen predicted that by 2015, 50% of enterprise mobility
applications would be HTML5 based. In another interview I conducted this week with Sencha's
CEO, Michael Mullany, he predicted that by 2014,50% of enterprise mobility
applications would be HTML5 based, 20% would be native, and 30% would
be a hybrid of HTML5.
from http://www.sys-con.com/node/2263927
2015년 Mobile OS Market share 예상
Android: 50.6%, iOS 20.6%, Microsoft 24.0%, Bada 1.8%
Source: Gartner (April 2012)
HTML5 Web App 기술 분야
5
SW 개발자

(Programming)

HTML5/Web App 개발자

(Programming)

Web designer
(Publishing)

ss

Java/C++/Objective C
Native
API

Algorithm

Compiling

HW
최적화


ARM

GPU

HTML5

HTML4

CSS3.0

CSS2.1

Flash

JavaScript
JavaScript
(system/module/logic) (DHTML)

DOM
Browser
Mobile Web Application 분류
6
¨ 

동작 및 배포 방식에 따른 구분
l 

l 

¨ 

Server hosted (except for App cache, Local Storage )
Hybrid (packaged and locally installed)

강좌 목표: Server Hosted의 Pure Web App 개발 기술 Practice

Remote Server

Web Data

Web Data

Web Data

HTML5 App
On target device

Native Web
App
WebView
(WebKit)

WebView
(WebKit)

HTML5
Native
App
Part
Container/Binder
(PhoneGap, AppMobi)
WebView
Binder
(WebKit)

Android/iOS

Android/iOS

Android/iOS

Browser
App Store로부터 Runaway
7
¨ 

App Store 통제
l 

l 

¨ 

run/own/censor ed by platform/OEM/carrier
Sale/in-app billing commission

시장 예: runaway from app store, into browser
l 

Amazon
- 

l 

Offline access, cloud sync, Native app look&feel GUI

Facebook
- 
- 

l 

App center strategy
W3C community group for browser fragmentation and billing

Financial Times
- 

Offline access, Native app look&feel GUI

- 

Auto download
Native to Web 이전 검토시 고려사항
8
주요 Factor

서비스 유형

Device 호환성

고려 사항
Web App으로 개발하기에 적합한 경우
1) 
News나 SNS와 같이 Info-tainment 성격의 서비스
2) 
웹 브라우저로 이미 서비스가 되고 있는 경우
3) 
서버 Update 및 Data sync가 빈번하게 발생하는 서비스
Multi- Platform/Device 대상인 경우 Web App이 적합함
Server-based

Server-based의 경우 Web App으로 Migration 용이함
( 단, T Store와 같이 http 방식이 아닌 TCP 소켓 통신의 경우 프로토콜의 수정 개발이 필요 )

HTML 5만으로 client 구현 가능한 경우
Data provision 방식
Client-based
Native component를 사용해야만 하는 경우

1) 
2) 
Performance-constrain
t

1) 
2) 

Web 기반 client를 개발해야 하는 비용 발생
간단한 App들이 이 범주에 속함

1) 
2) 
3) 
4) 

Hybrid 방식으로만 가능
NDK를 WebView에 정합하기 위한 비용 발생
NDK 사용하는 부분은 Cross-Platform하지 않음
T map이 대표적인 예임

기본적으로 Web App은 data loading, parsing, rendering 의 구조이기 때문에 Native 대비 성능이 느릴 수 밖에 없음
Hybrid 방식으로 Native component와 WebView 사이의 Data 전송이 발생하게 되면 Data 복사에 따른 추가의 overhead 발생
Ex) Device API 호출 시 overhead 발생
1) 
최적화되지 않은 기능을 많이 사용하면 안됨
Ex) Vector Graphic 위해 Canvas 2D를 많이 사용하면 성능이 저하됨
시장 사례 분석
9
¨ 

Melon 사례
l 

l 

¨ 

Server hosted: m.melon.com, t.melon.com
Hybrid: iOS 및 Android app

11번가 사례
l 

Server hosted: m.11st.co.kr

l 

Hybrid: iOS 및 Android app
Web App 개발 요구사항
10
¨ 

본 강좌에서 가정하는 Mobile Web app의 상위 수준 요구사항으로 이
를 만족하는 audio streaming용 Web application 개발 상품화 하는 시
나리오를 설정
l 

단말에서 구동되는 Mobile browser내에서 동작 해야함

l 

Native 수준의 뒤 떨어지지 않는 GUI/UX 를 제공하여야 함

l 

Audio playback을 제공해야함

l 

Cross-platform 지원 해야함
- 

Android 2.1/2.2/2.3/3.0/4.0 및 Chrome for Android

- 

IOS 3.0/4.0/5.0/6.0

- 

Blackberry OS 6.0/7.0

l 

UX 저하가 없는 수준의 성능을 제공 해야함

l 

작성한 코드는 다른 Application 개발에도 재활용이 가능해야함
Web App 개발 요구사항:
11

cross-platform
UI 상세 명세서 일부
12
¨ 

¨ 

아래의 3분류의 화면 Template 제공하고 화면간 이동 및 이동시
transition effect를 지원 해야함
노래 목록은 위 아래 scroll이 가능해야하고 이때 상단 및 하단 메뉴는
화면에 고정 되어있어야 함
고정

화면 전환
및 효과

화면 전환
및 효과
고정
Web App SW Arch. 구성 예
13
¨ 

Open source기반 Web application SW 구조
l 

¨ 

Open source 활용시 다양한 configuration이 가능하고 하나의 예임

Open source 선택시 필수 고려사항
l 

Community가 활성화정도, 안정 버전 release 주기

l 

License 종류, 회사 편향도
HTML5 audio application

UI
Framework

jQuery Mobile + plug-in
jQuery + plug-in

iScroll

(JS
Scroller)

Fast
Button

URL
Bar
Handle
r

Audio
FW

Fragmentation
Handling

Sound
Manager2

Modernizr

DOM (Document Object Model)
Browser
WebView (WebKit)
Android/iOS/Blackberry OS/Kindle Fire
Application processor, GPU
Page Speed: Mobile 11번가
14
jQuery Mobile (JQM)
15
¨ 

Smart phone과 tablet을 위한 touch 최적화된 UI widget 제공

¨ 

cross-platform을 진중히 추구하는 Touch 최적화 Web Platform

¨ 

jQuery plugin 및 widget pattern으로 개발됨: $.mobile

¨ 

Theming 지원: http://jquerymobile.com/themeroller/

http://jquerymobile.com/demos/1.1.0/
JQM Pagination
16
¨ 

단일 DOM tree 내에 2개 이상의 application view를 page로 구분하여
show/hide를 포함한 관리가 가능하도록 기능 제공
¨ 

개별 HTML에 저장된 page를 load하는 방식에 비해 속도, 데이터 공유를 위
해서 필수적인 기법
<body>
<div data-role="page“ id=“album_main”>
<div data-role="content">
</div><!-- /content -->
</div><!-- /page -->
<div data-role="page“ id=“page_home”>
<div data-role="header">
<h1>I’am header</h1>
</div><!-- /header -->
<div data-role="content">
</div><!-- /content -->
<div data-role="footer">
<h1> Footer </h1>
</div><!-- /footer -->
</div><!-- /page -->
<div data-role="page“ id=“page_playlist”>
<div data-role="header">
<h1>I’am header</h1>
</div><!-- /header -->
<div data-role="content">
</div><!-- /content -->
<div data-role="footer">
<h1> Footer </h1>
</div><!-- /footer -->
</div><!-- /page -->
</body>

page show 및 page간 전환시
network loading 지연 미 발생
JQM Widget
17
¨ 

지원하는 widgets
l 

Pages, dialogs, toolbars, listview, button, form element,
accordion, collapsibles
Listview 예제
18
<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.min.css" />
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.min.js"></script>
</head>
<body>
<div data-role="page">
<div data-role="header">
<h1>I’am header</h1>
</div><!-- /header -->
<div data-role="content">
<ul data-role="listview" data-inset="true" data-filter="true">
<li><a href="#">Acura</a></li>
<li><a href="#">Audi</a></li>
<li><a href="#">BMW</a></li>
<li><a href="#">Cadillac</a></li>
<li><a href="#">Ferrari</a></li>
</ul>
</div><!-- /content -->
<div data-role="footer">

<h1> Footer </h1>
</div><!-- /footer -->
</div><!-- /page -->
</body>
</html>
Navbar 추가
19
<div data-role="header" data-position="fixed">

<div data-role="footer" data-position="fixed">

<div data-role="navbar">
<ul>
<div data-role="navbar">
<li><a href="#">One</a></li>
<ul>
<li><a href="#">Two</a></li>
<li><a href="#">One</a></li>
<li><a href="#">Three</a></li>
<li><a href="#">Two</a></li>
</ul>
<li><a href="#">Three</a></li>
</div><!-- /navbar -->
</ul>
</div><!-- /footer -->
</div><!-- /navbar -->
</div><!-- /header -->

상단 고정

하단 고정
Multi page template
20
<body>
<!-- Start of first page -->
<div data-role="page"

id="foo">

Page foo

<div data-role="header>
<h1>Foo</h1>
</div><!-- /header -->
<div data-role="content">
<p>I'm first in the source order so I'm shown as the page.</p>
<p>View internal page called <a
</div><!-- /content -->

href="#bar" data-transition="pop">bar</a></p>

<div data-role="footer">
<h4>Page Footer</h4>
</div><!-- /footer -->
</div><!-- /page -->
<!-- Start of second page -->
<div data-role="page" id="bar">

pop

slide

Page bar

<div data-role="header">
<h1>Bar</h1>
</div><!-- /header -->

<div data-role="content">
<p>I'm the second in the source order so I'm hidden when the page loads. I'm just shown if a link that references my ID is beeing clicked.</p>
<p><a href="#foo"
</div><!-- /content -->
<div data-role="footer">
<h4>Page Footer</h4>
</div><!-- /footer -->
</div><!-- /page -->
</body>

data-transition="slide">Back to foo</a></p>
External page handling (1/2)
21
¨ 

현재 html이 아닌 별도의 html에 있는 page를 AJAX load후 DOM에
inject하는 기능
l 

<head> 내부 부분 parsing 하지 않음
- 

l 

JS 파일, <script> block, CSS를 load 하지 않음

Page-specific JavaScript 및 CSS는 직접 loading 해야함
- 
- 

Page div 내에 포함
<body> tag내에 포함
후 pageInit에서 초기화

<div data-role="content">
<a href="external.html"
</div><!-- /content -->

data-transition="pop">bar</a>

main.html

<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://jquery.mobile-1.1.0.min.css" />
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script src="http://jquery.mobile-1.1.0.min.js"></script>
</head>
<body>
<div data-role="page">
<div data-role="header">
<h1>I’am header</h1>
</div><!-- /header -->
<div data-role="content">
</div><!-- /content -->
</div><!-- /page -->
</body>
</html>

external.html
External page handling (2/2)
22
¨ 

Page prefetching
l 

external page를 전환 속도 개선을 위해 prefetch
<a href="prefetchThisPage.html" data-prefetch> ... </a>
programmatically load 방식
$.mobile.loadPage( pageUrl, { showLoadMsg: false } );

¨ 

DOM size 자동 관리
l 

l 

¨ 

숨겨진 page (pagehide event)의 DOM을 detach 후 제거 à
memory 사용량 개선 기능
show시 자동으로 AJAX를 통해 다시 load함

Page를 DOM에 caching 하는 기능
l 

hide시 DOM에서 detach후 해당 page를 별도로 cache
<div data-role="page" id="cacheMe" data-dom-cache="true">
Web based WISWYG Editor
23

¨ 
l 

¨ 

Codiqa
GUI editor

ThemeRoller Mobile
l 

Theme editor
ThemeRoller Mobile

Codiqa (charged)
UI 명세서 중간 점검
24
¨ 

JQM widget set 구성으로 구현 가능
l 

Page 3개, Listview, header/footer with position fixed

고정

화면 전환
및 효과

화면 전환
및 효과
고정
HTML5 Data- attribute
25
¨ 

data-* attribute 추가
l 

Custom attribute 정의하여 사용 가능
<li id="appDeveloperInfo"class="user" data-name="sangseok" data-company="SK planet"
data-lang="korea" data-food="Noodle">
<span>고맙습니다</span>
</li>

¨ 

저장값 접근 방식
l 

JavaScript/DOM API 활용
var appDeveloperInfo = document.getElementById(‘appDeveloperInfo’);
var appDeveloperName = appDeveloperInfo.getAttribute(‘data-name’);

l 

Jquery
jQuery.find(‘[data-name="sangseok"]’);

l 

Jquery Mobile
$("li:jqmData(role=’name’")
JQM Data- attribute
26
¨ 

JQM은 HTML 5 Data- attribute를 Widget 마다 정의하여 사용
l 

l 

¨ 

data-role, data-inset, data-position, data-corner, data-dom-cache
http://jquerymobile.com/demos/1.1.0/docs/api/data-attributes.html

JQM의 data enhance
l 

초기화시 해당 data- attribute에 따라 element를 선택후 해
당 element를 enhance를 수행함
- 
- 

새로운 CSS class 적용

- 
¨ 

Extra markup 추가
Event handler 등록

JQM 1.1.0에서는 data- attribute를 통한 enhance를 막는 기법
을 제공
l 

data-enhance=``false’’
JQM Event (1/2)
27
¨ 

Touch event
l 

¨ 

tap, taphold, swipe, swipeleft,swiperight

Virtual mouse events
l 

l 

¨ 

vmouseover, vmousedown, vmousemove, vmouseup
vclick, vmousecancel

Orientation change
l 

¨ 

orientationchange

Scroll events
l 

scrollstart, scrollstop
JQM Event (2/2)
28
¨ 

Page load events
l 

¨ 

Page change events
l 

¨ 

pagebeforeshow, pagebeforehide, pageshow, pagehide

Page initialization evets
l 

¨ 

pagebeforechange, pagechange, pagechangefailed

Page transition events
l 

¨ 

pagebeforeload, pageload, pageloadfailed

pagebeforecreate, pagecreate, pageinit

Layout events
l 

updatelayout
JQM Event Binding
29
¨ 

jQuery의 live() 또는 bind() 를 사용
l 

l 

l 

live(): jQuery selector에 현재 또는 미래에 match되는 모든
element에 event handler를 attach
bind():jQuery selector에 현재 match되는 모든 element에 event
handler를 attach
Delegate(): Document (default, 변경가능) Node에서 bubbling되
는 event에 대한 event handler를 attach

$( document ).bind( "pagebeforeload", function( event, data ){
// Let the framework know we're going to handle the load.
event.preventDefault();
// ... load the document then insert it into the DOM ...
// at some point, either in this callback, or through
// some other async means, call resolve, passing in
// the following args, plus a jQuery collection object
// containing the DOM element for the page.
data.deferred.resolve( data.absUrl, data.options, page );
});

$( 'div' ).live( 'pageshow',function(event, ui){
alert( 'This page was just hidden: '+ ui.prevPage);
});
JQM Method
30
¨ 

Jquery.mobile object를 통해 각종 method를 제공함
l 

$.mobile.changePage

l 

$.mobile.loadPage: external page load

l 

$.mobile.fixedToolbars.hide

l 

$.mobile.silentScroll
- 

l 

¨ 

주어진 Y위치로 onscroll trigger하지 않고 scroll

$.mobile.activePage

Full list는 아래에서 확인 가능
l 

http://jquerymobile.com/demos/1.1.0/docs/api/methods.html

//transition to the "confirm" page with a "pop" transition without tracking it in history
$.mobile.changePage( "../alerts/confirm.html", {
transition: "pop",
reverse: false,
changeHash: false
});
JQM VS Sencha Touch (1/2)
31
jQuery Mobile

Sencha Touch

개발사

jQuery 진영에서 개발

ExtJS 개발사에서 개발

개발자 Pool

125 contributor, 9 company supporter※

11 Sencha Employer

개발 Script

jQuery 기반

ExtJS 기반

개발 방식

마크업 기반 (Web Designer 친화적)

스크립트 기반 (JS Programmer 친화적)

테마 특징

CSS3 활용, 테마롤러 도구 지원

Sass 기반

핵심 라이브러리

jquery-mobile-1.0.js(210KB)
jquery.mobile-1.0css(81KB)
jquery.mobile-1.0.min.js(80KB) – 경량화 버전
jquery.mobile-1.0.min.css(48KB) – 경량화 버전

(1.1.1 기준)
sencha-touch.js (367KB)
sencha-touch.css (144KB)
sencha-touch-debug.js(746KB) –개발 버전
(2.0.0 기준)
sencha-touch.js (92KB)
sencha-touch.css (143KB)
sencha-touch-debug.js(423KB) –개발 버전

지원 모바일 플랫폼

iOS 3.2-5.0, Android 2.1-2.3/3.0, Window Phone 7-7.5, Black
Berry 6.0+ , Palm WebOS (1.4-2.0)/3.0,

iOS3.0 +, Android 2.1+ ,Black Berry 6.0 +

공식 Homepage

http://jquerymobile.com

http://sencha.com/products/touch

개발 버전

1.1.0

2.0

개발 난이도

중

상

특이사항

개방성: 순수 Open Source 과제로 운영
Product 개발 지원을 위한 외부 전문 Consulting 업체 운영중

Sench Touch Charts 유료버전 제공
AT&T의 Browser 기반 HTML5 AppStore

라이선스

MIT (jQuery 프로젝트와 동일)
GPL (jQuery 프로젝트와 동일)

Commercial S/W License (현재 무료)
Commercial OEM License(유료)
Open Source License (GPL v3)

*Saas: Ruby기반의 CSS 생생 library
※Mozilla, Palm, BlackBerry, Adobe, Jive, DotMobi, Nokia, DeviceAtalas, filament
JQM VS Sench Touch (2/2)
32

jQuery Mobile

<head> js파일 include

Sencha Touch

<head> </head>

<body>
<div data-role="page" id="sub" data-add-backbtn="true" data-fullscreen="true">
<div data-role="header" data-position="fixed" >
<h1>sub page</h1>
</div>
<div data-role="content">
<ul data-role="listview">
<li><a href="#">Acura</a></li>
<li><a href="#">Audi</a></li>
<li><a href="#">BMW</a></li>
<li><a href="#">Honda</a></li>
<li><a href="#">Hyundai</a></li>
</ul>
</div><!-- /content -->
</body>

Ext.regModel('Contact', {
fields: ['Name']
});
demos.ListStore = new Ext.data.Store({
model: 'Contact',
data: [
{Name: 'Acura'},
{Name: 'Audi'},
{Name: 'BMW'},
{Name: 'Honda'},
{Name: 'Hyundai'}
]
});
demos.List = new Ext.TabPanel ({
items: [{
title: 'Simple',
layout: Ext.is.Phone ? 'fit' : {
type: 'vbox',
align: 'center',
pack: 'center'
}
}]
});
UI 명세서 중간 점검
33
¨ 

Native 수준에 뒤 떨어지지 않는 GUI/UX 제공해야함

¨ 

Cross-platform 지원 해야함
- 
- 

¨ 

Android 2.1/2.2/2.3/3.0/4.0 및 Chrome for Android
IOS 3.0/4.0/5.0

CSS position:fixed property 지원 여부
- 

WebKit version 533미만 미지원

고정


화면 전환
및 효과
고정


position:fixed: window를 기준으로 위치를 고정
CSS position:fixed issue
34
¨ 

CSS position:fixed 정의
l 

l 

¨ 

element의 위치를 containing block이 아닌 window를 기준점으로 위치
를 정함
Web page 를 scroll하여도 위치가 고정되어 각종 메뉴구성에 쓰임

CSS position fixed 구현 방식
l 

Android 2.3 이상, iOS 5.0이상 정상 동작

l 

Android 2.2 이하 오동작
- 

l 

window기준으로 첫번째 rendering위치에 고정

IOS 4.0이하
- 

l 

고정


Web page의 끝 (마지막 element 다음)에 붙임

Android 2.3 삼성 단말 오동작
고정
CSS position:fixed 처리
35
¨ 

JQM에서 position:fixed 처리 방식
l 

Browser 엔진에서 지원시 사용

l 

Browser 엔진에서 미지원시 처리 방식
- 

Scroll 시작시 사라지게하고 종료시 다시 그려줌

- 

Page 최상단과 하단에 position:static으로 붙임
l 

¨ 

중간 위치로 scroll 되어있을시 화면에 보이지 않게됨

문제점
¤ 

첫번째 방식
- 

- 

¤ 

scroll시 JavaScript 수행을 중지시키는 경우 화면 update 문제 발생 (삼성
Android 2.3 단말 포함)
지속적으로 깜빡 거려서 UX 저하

두번째 방식
- 

UX 관점에서 application이라기 보다는 web page의 느낌임
Fixed toolbar 지원 대안 1
36
¨ 

overflow:scroll을 이용한 우회법
l 

l 

¨ 

Fixed toolbar의 position은 fixed가 아닌 absolute, static, inline을 사용하
여 scroll하는 영역 위 아래에 고정
overflow:scroll을 이용하여 content 영역만을 scroll

문제점
l 

overflow:scroll Android 2.3이하에서 미지원

l 

IOS 4.0이상 지원하나 두손가락 gesture를 사용: UX 일관성 깨짐

l 

지원이되더라도 화면 갱신 속도가 매우느림
position:fixed

viewport

position:inline

content
viewport

position:fixed

position:inline
IOS 5.0 부터는 -webkit-overflow-scrolling:touch 지원

content
overflow:scroll
JavaScript Scroller: iScroll
37
¨ 

iScroll JavaScript scroller: cubiq.org/iscroll-4
l 

overflow:auto, touch event, -webkit-transform을 활용한 개선

l 

-webkit-transfrom 미지원 단말 “top” property를 JS 변경

<div data-role="page">
<div data-role="header">
<h1>I’am header</h1>
</div><!-- /header -->
<div data-role="content">
<div class="wrapper">
<div class="scroller">
<ul data-role="listview">
<li><a href="#">Acura</a></li>
<li><a href="#">Audi</a></li> viewport
<li><a href="#">BMW</a></li>
<li><a href="#">Cadillac</a></li>
<li><a href="#">Ferrari</a></li>
</ul>
</div>
</div>
</div><!-- /content -->
<div data-role="footer">
<h1> Footer </h1>
</div><!-- /footer -->
</div><!-- /page -->

position:absolute

position:absolute

<div class = scroller>
-webkittransform:translate3d(0,dy,z)
z-index:1

<div class = wrapper>
overflow:hidden
position:absolute
z-index:1
touchmove event를 wrapper에 binding
iScroll 기능
38
¨ 

iScroll의 기능
l 

Pull to refresh

l 

Pinch zoom

l 

Scrollbar customize

l 

Transition mode
- 

l 

¨ 

webkit-transform-timing-function: cubic-bezier 사용

Touch 미지원시 mouse fallback

Public method
l 

refresh()

l 

scrollTo(x, y, time, relative)

l 

destroy
JQM내에서 iScroll활용
39
¨ 

JQM에서 page는 visible하기 전까지 그것의 height값이 계산되어지지 않음
l 

refresh 시점은 해당 page가 load되고 layout이 완료된후

¨ 

기타 JQM specific한 동작 styling handling이 필요함

¨ 

JQM widget plugin 활용 가능
l 

¨ 

https://github.com/watusi/jquery-mobile-iscrollview

제약 사항
l 

webkit-transform을 사용하더라도 속도가 느려지는 경우 있음

l 

scroller의 style은 CPU사용량이 최소한이 되도록 최적화 해야함
JQM 사용 Disclaimer
40
¨ 

Android 3.0 이하 및 iOS 4.0이하에 적용시에는 단말별 동작 검
증 필수
l 

성능 문제
- 

Style 값에 따른 CPU 과다 사용

- 

<a> link 포함시 단말별도 반응속도 저하

l 

Fixed element 동작 문제

l 

Transition 지원 문제
- 
- 

1.1.0부터는 target에 따라 문제가 있으면 fade로 fallback
그러나 문제가 없다고 detect되는 단말에서 실제 구현상의 이
슈, 또는 제조사 변경에 따라서 오동작 하는 경우가 다수임
Audio 기능 제공
41
¨ 

Audio관련 상세 requirement
l 

l 

LCD off시 연속 재생 지원

l 

Background mode 진입시 재생 지원

l 

¨ 

cross-platform으로 audio playback 지원

Playlist 지원

<audio> tag 지원
l 

Android 2.1 및 2.2 미지원
<audio> tag (1/2)
42
¨ 

IOS 4.0 >
l 

Only user action (e.g. onclick, touchevent) action can play
sound: audioElm.play()
<body onLoad="document.myMovie.play()"> will not work
<input type="button" value="Play" onClick="document.myMovie.play()> will work

l 

¨ 

autoplay is disabled by Apple on purpose

Browser in background mode (OEM customization)
l 

JavaScript timer paused

l 

Network paused

l 

Script execution paused

l 

setInterval suspended
<audio> tag (2/2)
43
¨ 

Audio tag event sequence on real devices
l 

Expected occurrence order
- 

l 

emptied → loadstart → durationchange → loadedmetadata → loadeddata →
canplay → play → playing → canplaythrough → pause → ended

Measured occurrence order
- 

IOS 5.1
emptied → loadstart → suspend → durationchange → loadedmetadata → canplay
→ stalled → play → playing → progress → canplaythrough → progress → stalled →
pause → ended

- 

Android 2.3 (Galaxy Note)
emptied → loadstart → durationchange → progress → durationchange →
loadedmetadata → loadeddata → canplay → canplaythrough → play → playing →
ended
Sound Manager 2
44
¨ 

<audio> tag 와 Flash를 이용한 cross-platform audio playback 지원
l 

¨ 

App developer에게는 단일 API를 제공

Sound Manager 2 API (program template)
<!-- include SM2 library -->
<script type="text/javascript" src="/path/to/soundmanager2.js"></script>
<script type="text/javascript">
soundManager.url = '/path/to/sm2-flash-files/'; // directory where SM2 .SWFs live
.
// soundManager.debugMode = false;
// The basics: onready() callback
soundManager.onready(function(){
// SM2 has loaded – no`w you can create and play sounds!
var mySound = soundManager.createSound({
id: 'aSound',
url: '/path/to/an.mp3'
// onload: myOnloadHandler,
// other options here..
});
mySound.play();
Not
});
</script>

verified for Mobile OS YET!!
Playlist 연속 재생
45
¨ 

LCD off 및 background 모드에서 연속재생 (Browser)
l 

<audio> tag의 구현 및 browser의 동작 방식에 따라 연속 재생 기
술적으로 불가
- 
- 

l 

iOS Safari (possible, but not robust)
Android browser (almost impossible)

기술 이슈 예
- 
- 

¨ 

LCD off mode시 JavaScript timer fire를 suspend
이미 DOM loading된 음악 재생은 가능하나, network를 통해
신규로 음악 loading 불가

현 시점에서 가장 안전한 방법
l 

Hybrid application으로 변경
- 

Hybrid application내의 WebView에서 HTML app loading시
LCD off 모드에서 연속 재생 가능
Native-like GUI: Full screen
46
¨ 

iOS의 Web App mode로 full screen 만들기
l 

Full screen 만들기
- 

l 

Status bar 설정
- 

l 

<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">

시작 화면
- 

¨ 

<meta name=”apple-mobile-web-app-capable” content=”yes>

<link rel="apple-touch-startup-image" href="loading.png" />

Android에서 Web app mode
l 

Full screen mode 미지원

l 

Bookmark 등록 지원

http://developer.apple.com/library/safari/#documentation/appleapplications/reference/SafariHTMLRef/Articles/MetaTags.html
Native-like GUI: Full screen
47
¨ 

URL bar hiding되는 browser에서 URL bar를 hiding시키는 조건
을 만족시키는 logic 구현
l 

l 

¨ 

Android 및 Web app mode가 아닌 iOS Safari browser 적용
Web page의 height를 URL bar height와 window.innerHeight를 더한 값
으로 set

Disclaimer
l 

l 

l 

Device 별 URL bar 크기 차이
URL bar hiding animation
도중 window는 계속적으로 resize 됨

var setupScroll = window.onload = function() {
if (ios) {
var height = document.documentElement.clientHeight;
if (iphone && !fullscreen) height += 60;
page.style.height = height + 'px';
} else if (android)
page.style.height = (window.innerHeight + 56) + 'px'
}
setTimeout(scrollTo, 0, 0, 1);
};

URL bar hiding animation도중 멈추는 현상 발생
(삼성 Galaxy Note/HD)

https://gist.github.com/1172490
Fast button 제작
48
¨ 

¨ 

browser의 onclick event는 double tap/panning 등의 처리로 지
연 (e.g. 300msec iOS)를 포함하고 이는 game에서와 같이 빠른
response를 필요로 하는 web app 개발시 제약임
onTouchStart는 지연없이 동작
¤ 

¤ 

<div ontouchStart=“doSomething()”> 구성 가능하나 누르는
순간 발생
onTouchEnd에서 발생시켜서 onclick을 emulation

http://cubiq.org/remove-onclick-delay-on-webkit-for-iphone
http://code.google.com/intl/ko-KR/mobile/articles/fast_buttons.html
Fast Button 예제: Matteo
49
function NoClickDelay(el) {
this.element = typeof el == 'object' ? el : document.getElementById(el);
if( window.Touch ) this.element.addEventListener('touchstart', this, false);
} NoClickDelay.prototype = { handleEvent: function(e) {
switch(e.type) {
case 'touchstart': this.onTouchStart(e); break;
case 'touchmove': this.onTouchMove(e); break;
case 'touchend': this.onTouchEnd(e); break; } },
onTouchStart: function(e) {
e.preventDefault(); this.moved = false;
this.theTarget = document.elementFromPoint(e.targetTouches[0].clientX, e.targetTouches[0].clientY);
if(this.theTarget.nodeType == 3) this.theTarget = theTarget.parentNode;
this.theTarget.className+= ' pressed';
this.element.addEventListener('touchmove', this, false);
this.element.addEventListener('touchend', this, false); },
onTouchMove: function(e) {
this.moved = true; this.theTarget.className = this.theTarget.className.replace(/ ?pressed/gi, ''); },
onTouchEnd: function(e) {
this.element.removeEventListener('touchmove', this, false);
this.element.removeEventListener('touchend', this, false);
if( !this.moved && this.theTarget ) { this.theTarget.className = this.theTarget.className.replace(/ ?pressed/gi, '');
var theEvent = document.createEvent('MouseEvents');
theEvent.initEvent('click', true, true);
this.theTarget.dispatchEvent(theEvent);
} this.theTarget = undefined;
} };
Fast Button: Google Clickbuster
50
google.ui.FastButton = function(element, handler) {
this.element = element;
this.handler = handler;
element.addEventListener('touchstart', this, false);
element.addEventListener('click', this, false);
};
google.ui.FastButton.prototype.handleEvent = function(event) {
switch (event.type) {
case 'touchstart': this.onTouchStart(event); break;
case 'touchmove': this.onTouchMove(event); break;
case 'touchend': this.onClick(event); break;
case 'click': this.onClick(event); break;
}
};
google.ui.FastButton.prototype.onTouchStart = function(event) {
event.stopPropagation();
this.element.addEventListener('touchend', this, false);
document.body.addEventListener('touchmove', this, false);
this.startX = event.touches[0].clientX;
this.startY = event.touches[0].clientY;
};
google.ui.FastButton.prototype.onTouchMove = function(event) {
if (Math.abs(event.touches[0].clientX - this.startX) > 10 ||
Math.abs(event.touches[0].clientY - this.startY) > 10) {
this.reset();
}
};

google.ui.FastButton.prototype.onClick = function(event) {
event.stopPropagation();
this.reset();
this.handler(event);
if (event.type == 'touchend') {
google.clickbuster.preventGhostClick(this.startX, this.startY);
}
};
google.ui.FastButton.prototype.reset = function() {
this.element.removeEventListener('touchend', this, false);
document.body.removeEventListener('touchmove', this, false);
};
google.clickbuster.preventGhostClick = function(x, y) {
google.clickbuster.coordinates.push(x, y);
window.setTimeout(google.clickbuster.pop, 2500);
};
google.clickbuster.pop = function() {
google.clickbuster.coordinates.splice(0, 2);
};
google.clickbuster.onClick = function(event) {
for (var i = 0; i < google.clickbuster.coordinates.length; i += 2) {
var x = google.clickbuster.coordinates[i];
var y = google.clickbuster.coordinates[i + 1];
if (Math.abs(event.clientX - x) < 25 && Math.abs(event.clientY - y) < 25) {
event.stopPropagation();
event.preventDefault();
}
}
};
document.addEventListener('click', google.clickbuster.onClick, true);
google.clickbuster.coordinates = [];
Fragmentation handling (1/2)
51
¨ 

Modernizr
l 

Device 상에서 Run time에 feature detection

l 

Feature detection scope
- 

CSS features: @font-face, border-image 등

- 

HTML5 features: application cache, canvas 등

- 

Plug- in을 추가하여 기능 확장
l 

https://github.com/Modernizr/Modernizr/tree/master/feature-detects
Fragmentation handling (2/2)
52
¨ 

사용 방법
l 

초기화

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>My Beautiful Sample Page</title>
<script src="modernizr-1.5.min.js"></script>
</head>
초기화 결과 저장
<html class="js canvas canvastext no-geolocation rgba hsla multiplebgs borderimage borderradius boxshadow
opacity cssanimations csscolumns cssgradients cssreflections csstransforms csstransforms3d csstransitions video
audio localstorage sessionstorage webworkers applicationcache fontface">
l 

Modernizr.load
Modernizr.load({
test: Modernizr.geolocation,
yep : 'geo.js',
nope: 'geo-polyfill.js'
});
Web App Platform Architecture
53
¨ 

WebKit engine 구조 및 동작

¨ 

Webkit rendering basics
WebKit Open Source Project
54
¨ 

Apple, Google 주도의 Open Source Project
¤ 

Committer/reviewer 분포

¤ 

Committer 자격
n 
n 

¤ 

Web 분야 투자/Leadership 간접 지표

10-20 good patch

Committer

Apple

39

6

Google

n 

Reviewer

24

32

총합

3명의 reviewer로부터 추천

Reviewer 자격
n 

최소 80 good patch

n 
¨ 

2

삼성전자

4명의 reviewer로부터 추천 (최소 한명은 다른 회사)

약 3백만 line으로 분야별로 전문 reviewer 활동

83

60

국내 committer: 4명
삼성전자: 2명 (EFL)
Company100: 1명 (Brew)
Intel: 1명(Gtk)
WebKit 구조
55
¨ 

WebKit은 Browser아닌 Web표준 처리를 위한 LIBRARY 집합
¤ 

¨ 

Mozilla Firefox, Google Chrome는 Browser가 Open Source

UI, Graphics, network등은 platform 별 별도 구현
¤ 

대부분의 성능의 격차는 port 구현에서 발생함

¤ 

HW 가속, Image Caching, API등은 port 별 구현

¤ 

Mac port는 미공개

Webkit open source 범위

Browser GUI

DB

Network

WebView (Widget, API)
HTML, CSS, JavaScript

Mac

Native
Widget

Cairo/Skia
(2D graphics)

Gtk

OpenGL ES
(3D graphics)

WebKit Graphics back-end 구조

Qt

Android

JavaScriptCore
(SFX, V8)

WebCore

WebKit
Native
Windowing

Efl

Plug
-in

Platform Port (HW 가속 포함)
Mac

Efl

Gtk

Qt

Android
Native Platform

Webkit 기반 Browser

메모리
관리
Chromium Browser
56
WebViewClient

Browser Process
TabContents

URL Bar

JS
FrontEnd

RenderViewHost

Gtk
Widget

RenderProcessHost
V8

Resource
DispatcherHost

Web Page
Gtk
Widget

JIT

IPC Channel

WebCoreSupport

RenderProcess
WebCore
Graphic
s
Layer
Tree

Render
Tree

Styl
e
Rule
s

DO
M
Tree

Parser

Loader

Glib main loop (Event Queue)

GPU
Process
Plugin
Process

File/DB

NPAPI::
PluginHost

RenderView

HTTP
stack

IPC Channel

IPC
Channel

UI FW

Skia (2D graphics)

Platform
Port
Resource Dispatcher

ResourceLoaderBridge

Gtk
X server

compositor

OpenGL ES / EGL

GPU Memory

GPU Process
URL bar

Webview

Window Buffer
Indicator

Frame Buffer
Android Browser
Multi-threaded
57
Browser Process

WebViewClient

Main Thread
Tool Bar

JS
FrontEnd
Webview

Canvas

Partially
Cached
DOM
Node

V8
JIT

WebViewCoreThread

WebCoreSupport

WebCore
Graphic
s
Layer
Tree

Render
Tree

Styl
e
Rule
s

DO
M
Tree

Parser

Loader

Canvas
PictureSet
RenderView
Message Handler (Event Queue)

UI FW

Platform
Port

Message Handler

Skia (2D graphics)

Gtk
Surface Manager

compositor

OpenGL ES / EGL

GPU Memory

Window Buffer
Indicator

Frame Buffer
Tizen Browser
Multi-threaded
58
WebKit

WebKit API
URL Bar
Evas
Object

JS
FrontEnd

WebCore

Animation Controller

WebCoreSupport

Page
Loader

DOM Data
JavaScriptCore
(SFX)
Interpreter
or
JIT

BackingStore
Evas Object

Platform
Port

Graphics
Layer
Tree

Render
Tree

Graphics
Layer

JS
Engine
Binder

Render
Layer

Style
Rule
s

Render
Object

DOM
Tree

Parser
CSS
Parser

Node

HTML
Parser

Graphics Port
Layer Renderer

GraphicsContext3D

Resource Load
Scheduler
Sub Resource
Loader
Main Resource
Loader

Network Port
GraphicsContext

Ecore Main Loop (Event Queue)
Pixman
(NEON)

UI FW

Cairo (2D graphics)

Evas
X server

Ecore
compositor

HTTP stack
(libsoup)

OpenGL ES / EGL

GPU Memory

Evas canvas
URL bar

Webview

Window Buffer
Indicator

Frame Buffer
DOM과 Render Tree 개괄
59
DOM Tree

HTMLDocument
2. addChild()

1. Element 생성

Render Tree

RenderView

HTMLHtmlElement

6. addChild()

3. rendererIsNeeded? YES

RenderBlock

5. setRender()

4. RenderBlock 생성

HTMLHeadElement
rendererIsNeeded? NO

HTMLTitleElement
http://image.google.com

HTMLStyleElement

<html>
<head>
<title>Google</title>
<style>…</style>
<script>…</script>
</head>
<body>
<div>
<nobr>
<span>
<a href=“http://news.google.com”>News</a>
</span>
<span>…</span>
</nobr>
</div>
</body>
</html>

HTMLScriptElement
RenderBlock

HTMLBodyElement
HTMLDivElement

RenderBlock

HTMLElement(nobr)

RenderInline

HTMLElement(span)
HTMLAnchorElement
Text
HTMLElement(span)

RenderInline
RenderInline
RenderText
RenderInline
WebKit Rendering Basics(1/4)
60
¨ 

내부 Data Structure

<html>
<head>
</head>
<body>
<p> hello</p>
<div class=“page” >
<p>world</p>
<div>
parsing
</body>
</html>
.page {
position: absolute;
width: 100%;
height: 100%;
-webkit-transform: translate3d(0, 0, 0);
}

Document

RenderVie
w

<html>

<head>

RenderRoot
Layer

조건별 Layer 생성
DOM node
attach

<body>

<p>

hello

<p>

RenderLayer1

<div>

RenderText:”H
ello”

RenderText:
”World”

world

HTML/CSS file

DOM Tree

Render Tree

RenderLayer Tree
WebKit Rendering Basics(2/4)
61
¨ 

내부 Data Structure

RenderLayer 생성 조건

1) root object for the page
2) explicit CSS position properties (relative, absolute or a transform)
3) transparent
4) overflow, an alpha mask, reflection
5) <canvas> element with a 3D (WebGL) context
6) <video> element

RenderVie
w

RenderRoot
Layer

Hello
World

RenderBoxModelObject::
requiresLayer()
Z ordering

RenderLayer

RenderText:
”Hello”

GraphicLayer

RenderText:
”World”

Render Tree

RenderLayer
Tree

GraphicsLayer Tree
(Texture on GPU)
WebKit Rendering Basics(3/4)
62
¨ 

Painting 절차: SW path
¤ 

하나의 graphic buffer를 할당

¤ 

Z order에 따라 뒤에서 앞으로 칠함

Hello

n 
n 

¨ 

Hello를 주어진 buffer에 paint
World를 Hello를 paint한 buffer에 칠함

World

GraphicsContext: Graphic Buffer

Painting 절차: HW accelerated path: Accelerated Compositing by GPU
¤ 

CPU graphics buffer와 GraphicsLayer 별 GPU buffer 생성

¤ 

Layer 별로 painting

¤ 

모든 결과를 sync하여 compositing
Hello

Hello
World

GraphicsContext:
Graphic Buffer on CPU

GraphicsContext:
Graphic Buffer on GPU

World
Compositing
by GPU (Open GL ES)
WebKit Rendering Basics(4/4)
63
¨ 

HW accelerated path: Accelerated Compositing by GPU
¤ 

CSS 2D/3D transformation시 “World”를 animation 각도에 따라 매번 다시 paint 하지 않고
만들어진 texture를 GPU로 회전 후 기타 Layer와 compositing 수행
Hello

GraphicsContext:
Graphic Buffer on CPU
¨ 

Hello

GraphicsContext:
Graphic Buffer on GPU

Compositing
by GPU (Open GL ES)

장점
¤ 

¤ 

¨ 

속도가 CPU 대비 “order of magnitude”로 빠름
3D transformation은 Accelerated Composting이 enable되어 있을때만 사용 가능

단점
¤ 

¨ 

메모리 사용량 증가: GPU memory를 별도로 할당

iOS 및 Android 4.0이상에서 지원
Silky Smooth Scroll 기술(1/3)
64
¨ 

“60 frame/sec” rule: 인간의 눈 고려시 최적 값
¤ 

¨ 

최소 16 msec 마다 한번씩 화면 갱신 필요

Reflow 연산: 50 msec~(600MHz@ARM Coretex-A8)
¤ 

주어진 DOM Tree에서 invalidate된 화면을 다시 re-paint

Finger touch
viewport
Silky Smooth Scroll 기술(2/3)
65
¨ 

BackingStore
¤ 

¤ 

한번의 scroll로 이동 가능한 영역에 대해서 pre-rendering된 결과를
image로 caching
사용자 Scroll시 pre-rendering된 image의 일부를 cut-n-paste를 하여
viewport로 복사 Reflow/Repaint 제거

Single Image Buffer
Silky Smooth Scroll 기술(3/3)
66
¨ 

BackingStore
¤ 

¤ 

한번의 scroll로 이동 가능한 영역에 대해서 pre-rendering된 결과를 image로 caching
사용자 Scroll시 pre-rendering된 image의 일부를 cut-n-paste를 하여 viewport로 복사
Reflow/Repaint 제거

RenderVie
w

RenderRoot
Layer

Z ordering

RenderLayer

RenderText:
”Hello”

RenderText:
”World”

GraphicLayer

Viewport보다 큰 영역을
미리 rendering해서 image cache를 해둠
사용자 panning시 이미 rendering된 이미지를
복사해주기만 함
Mobile Web App 성능 Factor
67
¨ 

Battery Life
¨ 

CPU utilization
¨ 
¨ 

¨ 

No JS animation, use CSS animation
Repaint/layout를 최소화

Memory bus utilization
¨ 
¨ 

image file의 크기 최소화

¨ 
¨ 

Cache miss시 external DRAM read/write발생

JavaScript실행시 heap memory 사용량을 inspector로 측정

external device: WiFi, Modem, GPS, Decoder
¨ 
¨ 

¨ 

압축을 통해 정보량을 최소화
필요시에만 정보를 주고 받기

Latency (RTT)
¨ 

DNS look ups, HTTP request 송수신

GPU benefits and pitfalls

¨ 
¨ 

Composited elements는 4배까지의 메모리 사용량 증가 가능

Battery 소진 주요 요소
CPU: P = CV2f
LCD: dimm level (color AMOLED)
WiFi/3G/LTE: Data 송수신
SDRAM: Data 읽기/쓰기
Flash: Data 읽기/쓰기
End-to-End 성능 최적화 (1/2)
68
l 

성능 최적화 guide 및 tip

l 

(성능 === Money) // true

Delay
0-100ms

instant

100-300ms

Feels sluggish

300-1,000ms

Machine is working...

1s+

Mental context switch

10s+

I’ll come back later

Usability Engineering – Jakob Nielsen, 1993
End-to-End 성능 최적화 (2/2)
69

From W3C Navigation Timing specification
Front-end (FE) 최적화 Guide
70

¨ 
¨ 

Part 1: Graphics/Animation
Part 2: Parsing/Layout/Rendering

¨ 

Part 3: JavaScript
Part 4: DOM Event

¨ 

Part 4: Networking/Loading

¨ 

Part 5: jQuery

¨ 
FE 성능 개선 Guide – Part 1
71

¨ 

Graphics/Animation
2D/3D Animation
72

¨ 

¨ 

[RULE] CSS 2D/3D transforms를 이용한 2D/3D animation 구현
은 HW 가속 Accelerated Compositing 기능이 제공 되는 Mobile O
S 에서만 사용한다
Mobile OS에서 HW 가속 Accelerated Compositing 지원 현황
iOS 3.0
지원 여부

¨ 

iOS 4.0

iOS 5.0

Android 2.1

Android 2.2

Android 2.3

Android 3.0

Android 4.0

X

O

O

X§

X§

X§

X

O

JavaScript를 통한 지원 여부 검사 방법
¤ 

User agent를 통해 Mobile OS 버전을 알아내서 활용 가능
n 

해당 property는 read/write 가능하여 비추천
var ua = window.navigator.userAgent;

Mozilla/5.0 (Linux; U; Android 2.3; en-us) AppleWebKit/999+ (KHTML, like Gecko) Safari/999.9
¤  Modernizr※ JavaScript library 활용 (추천)
n 
n 

csstransforms, csstransforms3d, csstransitions
Android 2.1-2.3은 true이나 제대로 동작하지 않음

※ http://www.modernizr.com: MIT&BSD licensed opens source project for HTML 5 and CSS feature detection
§ http://daneden.me/2011/12/putting-up-with-androids-bullshit/ single property animation 만 적용 가능
2D/3D Animation
73

¨ 

¨ 

[RULE] Animation이 수행되는 layer 수를 최소화 하고 크기를 power of 2
로 adjust 하자. Layer 수의 증가는 animation시 사용하는 GPU메모리 사용
량을 증가시킴
Open GL ES Texture 생성 제약 조건※
¤ 

Texture의 width와 height는 power of 2 이어야 함
n 

¤ 
¤ 

PowerVR chip의 PVRTC compressed image 사용시 정사각형 이어야 함: iOS d
evice 계열에서 사용
http://joehewitt.com/2011/10/05/fast-animation-with-ios-webkit
Max size limit 있음
n 
n 

¨ 

2, 4, 8, 16, 32, …, 1024

OpenGL ES 1.0 SGX: 1024x1024
OpenGL ES 2.0 SGX: 2048x2048

Layer의 크기가 257x257이면 실질적으로는 512x512 크기의 texture를 생
성하게 됨
¤ 

다수의 layer를 위와 같이 생성시 비효율적인 메모리 사용 증가

※ Graphics Chip Vendor 별로 특성 확인 필요
2D/3D Animation
74

¨ 

¨ 

¨ 

[RULE] Animation을 수행하는 영역은 as simple as possible 하게
유지하자
Animation 대상 block이 painting 비용 관점에서 복잡해질수록 Anim
ation시 사용하는 Texture를 초기 생성하는 지연증가로 Animation 개
시 지연 발생
Not simple 의미: !(painting cost가 높음)
n 

CSS filter, shadow, canvas, SVG, 과도한 DOM node 개수, scaled된 image 등

일반 text

비용증가à
Texture 생성 시간 증가à
animation 개시 시간 증가
이해를 하고 꼭 알고 쓰자

Blurred text
2D/3D Animation
75

¨ 

[RULE] Animation 시나리오상 animation 대상 block은 그것의 visu
al change가 발생하지 않도록 작성하자
¤ 

변경시 마다 texture를 재생성해야하고 texture를 caching 하여 재활용 하는 mo
bile OS에서는 cache 효율성이 낮아짐

¤ 

http://www.w3schools.com/css3/tryit.asp?filename=trycss3_transition2
n 

width, height가 변경되는 경우와 그렇지 않은 경우 비교

Animation 도중 text blurring 시나리오
이해를 하고 꼭 알고 쓰자
2D/3D Animation
76

¨ 

¨ 

[RULE] JavaScript Library에서 제공하는 animation 효과도 mobile
OS 별로 이해하고 사용하자
Android 단말에서의 page transition의 smoothness와 동작여부의
변이가 매우 심함
¤ 

¨ 

jQuery Mobile 1.0/Sencha Touch는 기본적으로 animation effect (flip, slide
등)을 CSS 3D transformation을 사용하여Accelerated Compositing 적용 받
으나 Platform 버전별로 성능 변이가 매우 높음

iOS 버전별, Android 버전별 성능을 확인후 사용 해야함
¤ 

JS Profiling 결과를 첨부 하자
2D/3D Animation
77

¨ 

¨ 

¨ 

[RULE] Compositing layer 각각은 width와 height의 제약이 있으므
로 element의 크기를 너무 크지 않게 해야한다
Unless otherwise, mobile OS의 GPU 가속 engine에서 직접 쪼개
거나 failure 발생
각 chunk를 직접 쪼개고 쪼개진 chunk 단위로 animation이 수행되도
록 한다: chunk size handling하는 webkit logic을 직접 분석 해서 포
함하자
.carousel {
-webkit-transform: translate3d(0,0,0); /* or translateZ(0); */
}
.carousel {
-webkit-transform: translate3d(0,0,0); /* or translateZ(0); */
}
.carousel-pane {
-webkit-transform: translate3d(0,0,0); /* or translateZ(0); */
}
HW 가속 Layer 이용
78

¨ 

¨ 

image zoom in/out시 잘 보이기 위해서 그것을 HW compositing la
yer로 mapping 가능
해당 image에 아래 CSS 적용
¤ 

¨ 

-webkit-transform:translate3d(0,0,0) à 별도 layer에 mapping

resource 사용량이 늘어남
Canvas 2D/3D
79

¨ 
¨ 

[RULE] Canvas 2D는 속도가 매우 느리므로 사용을 자제 하자.
기존 HTML/CSS로 표현 불가한 것이 있을 경우 painting 속도를 충분
히 분석하고 사용하자
¤ 

¨ 

`12년 Canvas 2D에 대한 HW 가속이 진행중이고 성능 개선이 확인된 후에만 사
용하도록 하자

[RULE] Canvas 3D는 현시점 (`12년 1월)에서 Mobile 단말에서 미지
원이므로 사용하지 말자
성능 개선 Guide – Part 2
80

¨ 

Parsing/Layout/Rendering
CSS overflow property
81

¨ 
¨ 

[RULE] CSS의 overflow:scroll 속성의 사용은 신중히하자
div
Platform 별 대처 방식
¤ 

iOS에서는 two finger로 scroll 가능
n 
n 

¤ 

Android는 one finger scroll 가능
n 

¨ 

-webkit-overflow-scrolling: touch
iOS 5 부터 지원: native 수준 성능 제공

{
width:150px;
height:150px;
overflow:scroll;
}

3.0 이후 버전만 scroll 지원 (2.3 이하 미지원)

단점
¤ 

일반 화면 scroll에 비해 속도가 느림
n 
n 

¤ 

BackingStore에 cache 되지 않고 매번 Render Tree으로부터 다시 paint
iOS 5와 Firefox는 별도의 Layer로 구성되고 layer별 BackingStore 지원으로 빠르나 메모
리 사용량 증가

poor discoverability: 사용자가 scrollable 여부 인지하기 힘듦
n 

화면 자산때문에 scroll bar를 지원하지 않음
CSS fixed positioning
82

¨ 

[RULE] 꼭 필요한지 요구사항을 확인하고 browser 별 지원여부를 확인하고
사용한다

¨ 

현재 mobile OS에서는 cross-platform하게 동일 UX로 제공되지 않고 있음

¨ 

iScroll, Scrollability등을 사용 가능하나 성능 문제 및 잠재 defect이 존재함

¨ 

http://bradfrostweb.com/blog/mobile/fixed-position/
Layout 발생 및 비용 분석
83

¨ 
¨ 

[RULE] layout 발생을 최소화 하자
Layout은 전체 또는 부분 DOM traversing을 수행 후결과로 repaint를 수반
¤ 
¤ 

¨ 

DOM tree가 커지면 layout 비용은 비례하여 증가함
¤ 

¨ 

Layout은 serialize된 CPU intensive 작업
Repaint는 대량의 data copy 연산 발생 야기 à battery 소진
11st (3,370개), mobile 11st (785개), latimes.com (5,563개), lemonde.fr (6,85
6개)

Layout 발생 조건
¤ 
¤ 
¤ 
¤ 
¤ 

Browser window resize, Orientation 변경
style information 정보 요청
DOM 변경: Adding, removing, updating nodes
display property, CSS box model 값 변경
Desktop 에서의 zooming 및 scrolling
n 

Mobile 단말에서 layout 없이 zoom factor에 따라 content를 repaint
Layout 비용 절감
84

¨ 

¨ 

[RULE] html문서와 해당 CSS loading 직후 layout에 필요한 contai
ning block의 width와 height 최대한 빨리 계산 될 수 있도록 하라
Width와 height를 빨리 알리는 방법 예제
¤ 
¤ 

¤ 

Image의 width와 height는 명시하거나, parent node를 block flow화 하라
AJAX로 HTML을 삽입시에도 삽입되는 공간을 미리 잡고 width height 명시후 bl
ock flow화 하라
<div> overflow:scroll이나 auto를 사용하여 block 크기를 변경하지 않을 수 있음
à 속도 문제 발생 가능
Layout 비용 절감
85

¨ 

¨ 

[RULE] 동적 또는 일시적인 정보 출력은 기존 layout을 변경을 하지 않
는 방식으로 출력하자
Layout을 변경하지 않는 문서 적재 방식 예제
¤ 

기존 RenderLayer의 일부가아닌 별도의 RenderLayer가 생성되어서 화면에 ov
erlay 되는 경우
n 
n 

¤ 

¨ 

Z-ordering, fixed positioning
Notification, ad등에 활용

화면 상단보다는 최하단에 배치

lemonde.fr 비효율저긴 사례
¤ 

Page load 완료후 DOM Node를 화면 최상단에 삽입하면서 animation 효과로
전체 페이지를 아래로 밀어 내림
n 

매 animation frame 마다 전체 page layout을 수행하고, 전체 page를 repaint하는 최
악의 활용 예제
Layout 비용 절감
86

¨ 
¨ 

[RULE] styling 변경은 꼭 필요시, 꼭 필요한 부분만 국소적으로 하라
Text 크기 변경, margin/padding/border 크기 변경, font type 변경등
은 전체 또는 부분 page layout 수행을 야기한다
¤ 

Layout후 해당 부분은 다시 repaint를 수행

CSS Box Model
¨ 

Repaint 만 발생하는 경우 (layout 미 발생)
¤ 

Visibility, colors, transforms, backgroud images, transparency
Repaint 비용 최소화
87

¨ 

[RULE] element의 individual style을 반복적으로 변경하지 말고 cla
ss name으로 일시에 변경하라
// bad
var left = 10, top = 10;
el.style.left = left + "px";
el.style.top = top + "px";
// better
el.className += " theclassname";
Frameset/iframe 처리
88

¨ 

¨ 
¨ 

[RULE] Frameset, iframe와 같이 scroll bar에 의한 content scroll
을 사용하는 방식은 쓰지 말자
Mobile browser에서는 scroll bar를 미지원
Frameset/iframe은 frame 내의의 content 크기를 계산하여 키워서
도시하는 frame flattening 적용
¤ 

¨ 

iOS, Android, Meego

Frame flattening
¤ 
¤ 

Bug-prone
의도되지 않은 방식으로 엔진
에 의해 Layout 변경됨
CSS 속성: -webkit-text-size-adjust
89

¨ 

¨ 

¨ 

[RULE] iOS에서 text readability 개선을 위해 text block의 속성으로
–webkit-text-size-adjust를 활용하자
별도의 zooming이나 text 재배치 없이도 text를 읽을수 있도록 자동으
로 키워줌 (Mobile Safari only)
iOS 1.0 이상에서 readability를 개선
¤ 

¨ 

삼성 버전 Android 지원 예정

구문
-webkit-text-size-adjust: none | auto | <percentage>;
None: The text size is not adjusted.
Auto: The text size is automatically adjusted for Safari on iPhone.
<percentage>: The size in percentage at which to display text in Safari on iPhone.
Image 자원 관리
90

¨ 

[RULE] 최종 display 되는 크기와 일치하는 image를 사용하자
[RULE] OS별 webkit 엔진의 image cache 관리방식을 고려하여 im
age의 크기를 조정하자

¨ 

iOS의 image 처리 제약 조건

¨ 

¤ 

¤ 

¨ 

Decoding된 GIF, PNG, TIFF의 크기가 3MB (128MB RAM), 5MB (>256MB
) 일 경우 화면 도시 불가
JPEG는 32M pixel까지 가능하나 실질적으로는 2M pixel로 subsampling 됨
à 화질 저하 발생

성능 저하 문제
¤ 

Decoding된 image의 크기가 1-3MB 이상일 경우 WebKit 내부의 decoded im
age cache에 caching을 하지 않고 rendering후 cache에서 drop à 화면에 도
시할 때마다 decoding을 해야하므로 매우 성능이 나빠질 개연성 발생
Viewport meta tag
91

¨ 
¨ 

[RULE] mobile site/app는 적절히 viewport를 명기하자
Viewport의 property를 적절히 setting 해야함
¤ 
¤ 
¤ 

iOS, Tizen default width 980 pixel
Desktop page는 default (980)을 사용
Mobile site/web app은 “device-width”를 사용

<meta name = "viewport" content = "width = device-width">
<meta name = "viewport" content = "initial-scale = 2.3, user-scalable = no“>

http://developer.apple.com/library/IOs/#documentation/AppleApplications/Reference/SafariWebContent/UsingtheViewport/UsingtheViewport.html
Viewport meta tag
92

Property

Description

width

The width of the viewport in pixels. The default is 980. The range is from 200 to 10,000.
You can also set this property to the constants described in “number.”
Available on iPhone OS 1.0 and later.

height

The height of the viewport in pixels. The default is calculated based on the value of the width property and the a
spect ratio of the device. The range is from 223 to 10,000 pixels.
You can also set this property to the constants described in “number.”
Available on iPhone OS 1.0 and later.

initial-scale

The initial scale of the viewport as a multiplier. The default is calculated to fit the webpage in the visible area. Th
e range is determined by the minimum-scale and maximum-scaleproperties.
You can set only the initial scale of the viewport—the scale of the viewport the first time the webpage is displaye
d. Thereafter, the user can zoom in and out unless you setuser-scalable to no. Zooming by the user is also limit
ed by the minimum-scale andmaximum-scale properties.
Available on iPhone OS 1.0 and later.

minimum-scale

Specifies the minimum scale value of the viewport. The default is 0.25. The range is from >0 to 10.0.
Available on iPhone OS 1.0 and later.

maximum-scale

Specifies the maximum scale value of the viewport. The default is 1.6. The range is from >0 to 10.0.
Available on iPhone OS 1.0 and later.

user-scalable

Determines whether or not the user can zoom in and out—whether or not the user can change the scale of the
viewport. Set to yes to allow scaling and no to disallow scaling. The default is yes.
Setting user-scalable to no also prevents a webpage from scrolling when entering text in an input field.
Available on iPhone OS 1.0 and later.
Language encoding
93

¨ 
¨ 
¨ 

[RULE] content의 encoding type을 반드시 명기 하자
[RULE] AJAX로 보내지는 HTML 문서도 encoding type을 반드시 명기하자
WebKit Text Encoding Source
Encoding type 명기법
enum EncodingSource {
¤ 

HTTP header에 명기 (the best way)
n 
n 

¤ 

HTML 문서 header에 명기
n 

¨ 

Content-Type: text/xml; charset=ISO-8859-1
AJAX의 response header에서도 동일하게 명기
<meta http-equiv="Content-Type" content="text/html;

DefaultEncoding,
AutoDetectedEncoding,
EncodingFromXMLHeader,
EncodingFromMetaTag,
EncodingFromCSSCharset,
EncodingFromHTTPHeader,
UserChosenEncoding,
EncodingFromParentFrame }
charset=utf-8“>

Encoding auto-detector 단점
¤ 

Auto-detector 동작 조건:
n 

¤ 

Encoding type이 명기되어 있지 않고 && default encoding setting되어 있지 않고, paren
t frame이 있지만 parent frame도 auto-detecting일 경우 auto-detector가 동작

Auto detecting algorithm은 정확하지 않고 수백 msec 수준의 지연 발생

WebKit-r103911SourceWebCoreplatformtextTextEncodingDector.h
Language encoding
94

¨ 

¨ 

[RULE] 가능하면 HTTP response header에 language encoding
을 명기하라
Webkit엔진 기반 Browser는 encoding type이 알려질때까지 docum
ent를 buffering
¤ 

HTML parsing과 Script 수행이 바로 되지 않는 지연 발생
Bytes Buffered

Configuration

Firefox 3.5

Chrome 3.0

IE 8

Tranfer-Encoding: chunked

1134

1056

300

Content-Type: text/html
Tranfer-Encoding: chunked

204

1056

341

Content-Type: text/html
Tranfer-Encoding: chunked
...
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

166

204

218

Content-Type: text/html; charset=utf-8
Tranfer-Encoding: chunked

204

280

300

http://www.kylescholz.com/blog/2010/01/performance_implications_of_charset.html
http://www.w3.org/TR/REC-html40/charset.html#h-5.2
Content Size 줄이기
95

¨ 

[RULE] HTML, JS, CSS는 Minifying 하자
¤ 

¨ 

White space, indent, line break 제거

[RULE] gzip, deflate를 통해 compression을 하자
¤ 

Gzip-friendly content 구성 방법론
n 
n 
n 
n 

¤ 

CSS key-value를 가능한 동일 순서로 나열 (e.g. alphabet 순서)
HTML attribute를 가능한 동일 순서로 나열
일관성 있는 casing 사용 (e.g. lowercase만 사용)
일관성 있는 quoting for HTML tag attribute (e.g. always single, always double)

Gzip (deflation) 원리
n 
n 

Duplicated string을 찾음
두 번째 중복 string 발생시 첫번째 found string으로의 pointer로 대체
n 

n 

Pointer는 distance와 length의 pair

즉, 중복 string이 많아야 압출률이 높아진다
Web에서의 Image 사용 통계
96

¨ 

Image가 차지하는 비중이 63%에 이름

http://httparchive.org/interesting.php#bytesperpage
Image Size 줄이기 (1/2)
97

¨ 

[RULE] 가장 적합한 image format을 선정하자
¤ 

PNG (Portable Network Graphics)는 GIF보다 압축 성능우수
n 
n 

¤ 
¤ 

10x10 pixel 정도의 작은 그림은 GIF 사용
Photographic-style image는 JPG 사용
n 

¤ 

¨ 

Continuous tone (e.g. gradient)는 lossy compression

Logo나 line art에는 GIF 사용
n 

¤ 

PNG는 Zip compression 압축률 > GIF는 LZW compression 압축률
GIMP “indexed”로 생성 (RGB 말고)

JPG 사용시 이미지 뭉개짐 현상 발생

BMP와 TIFF는 사용하지 말라

[RULE] 추가적인 image compressor로 좀더 크기를 줄이자
¤ 

Image compressor로 추가 무손실 압축
n 
n 

JPG: Jpegtran, jpegoptim
PNG: OptiPNG, PNGOUT
Image Size 줄이기 (2/2)
98

¨ 

[RULE] 추가적인 image compressor로 좀더 크기를 줄이자
¤ 

Image compressor로 추가 무손실 압축
n 
n 

¨ 

JPG: Jpegtran, jpegoptim
PNG: OptiPNG, PNGOUT

[RULE] lossy compression으로 좀더 크기를 줄이자
¤ 
¤ 

눈에 띄는 Visual 변화 없이 크기를 줄일 수 있음
활용 tool: http://www.smushit.com/ysmush.it/

http://calendar.perfplanet.com/2011/lossy-image-compression/
사용되지 않는 CSS 제거
99

¨ 

¨ 

[RULE] 해당 페이지에서 쓰이지 않는 CSS는 제거해야 page renderi
ng이 빠르게 수행된다
CSS 제거 점검 사항
¤ 
¤ 

현재 page에서 사용하지 앟는 inline style block을 제거
여러 page에서 공유 되는 External CSS는 작은 크기로 쪼개서 해당 page에만
적용 가능하도록 함

¤ 

¤ 

¨ 

Page start-up 초기에 필요하지 않는 CSS는 별도의 CSS 파일로 쪽개고 “onloa
d” event이후에 loading 하자
JS로 loading되는 CSS 파일의 경우도 쓰이는지 점검하자

사용되지 않는 CSS selector를 찾아주는 tool
¤ 
¤ 

https://github.com/driverdan/cssess
Bookmarklet에 JS 삽입 “cssess-min.js “ 삽입
CSS 삽입 위치
100

¨ 

¨ 

[RULE] rendering 성능을 위해서 CSS, inline style block은 문서의
header에 위치 시키자
Stylesheet 위치에 따른 제약 사항
¤ 

¤ 

¨ 

WebKit 엔진은 모든 external stylesheet을 load할 때까지 rendering을 block
함
Inline style block은 reflow를 야기해서 content를 shift 시킬 가능성이 높음

아래 webkit code에서와 같이 모든 style sheet의 적재가 끝나지 않으
면 해당 문서의 style 값 계산을 미루어 layout과 그에 따른 rendering
까지가 지연이 된다
void Document::styleSelectorChanged(StyleSelectorUpdateFlag updateFlag)
{
// Don't bother updating, since we haven't loaded all our style info yet
// and haven't calculated the style selector for the first time.
if (!attached() || (!m_didCalculateStyleSelector && !haveStylesheetsLoaded()))
return;
CSS 기능중 신중함이 필요한 기능
101

¨ 

[RULE] 하기 CSS 기능은 CPU 사용률이 매우 높기 때문에 신중히 사
용하자

¨ 

Rounded corners

¨ 

Box-shadow, Text-shadow
¤ 

Shadowing은 static bitmap이미지가 아니고 매번 repaint때마다 evaluate 됨

¨ 

Backgroud-position

¨ 

Background-repeat

¨ 

Multiple background images
Border-image

¨ 

Gradients

¨ 
Rounded Corners 표현
102

¨ 

[RULE] 속도를 위하여 CSS 3 specification의 border-radius, -moz
-border-radius, -webkit-border-radius 신중히 사용
div
{
border:2px solid #a1a1a1;
padding:10px 40px;
background-image: url("http://img1.coupangcdn.com/image/dd/64/30/15306430_bannerList.jpg");
width:300px;
border-radius:25px;
-moz-border-radius:25px; /* Firefox 3.6 and earlier */
}

Sample pattern
Shadows
103

¨ 
¨ 
¨ 

[RULE] CSS 3 specification의 text/box shadow를 신중히 사용
-webkit-box-shadow, box-shadow
Shadowing 영역은 repaint 마다 매번 다시 shadowing 영역에 대한 값들을
evaluation 수행하므로 매우 비싼 연산
¤ 

이미지와 같이 once decoded, reuse repeatedly가 아님

div
{
width:300px;
height:100px;
background-color:yellow;
-moz-box-shadow: 10px 10px 5px #888888; /* Firefox 3.6 and earlier */
box-shadow: 10px 10px 5px #888888;
border-radius:25px;
background-image:url("http://img1.coupangcdn.com/image/dd/64/30/15306430_bannerList.jpg");
}

¨ 

Div 영역에 box-shadow시 webkit에서 scroll 성능이 느린 defect 미해결
¤ 

https://bugs.webkit.org/attachment.cgi?id=80611&action=prettypatch
Gradient
104

¨ 

¨ 

¨ 

[RULE] –webkit-linear-gradient등은 scroll시 CPU를 지속적으로 소비하여
webkit-transfrom 기반 scroll 성능을 저하시킴으로 mobile에서는 신중히
적용

background-image: -webkit-linear-gradient(linear, left top, left b
ottom, from (#666), to(#222) from jQuery Mobile의 CSS
CSS gradient 소개
¤ 

http://www.webkit.org/blog/1424/css3-gradients/
<canvas> 성능
105

¨ 

¨ 

[RULE] HTML 5 canvas 성능은 mobile에서 매우 느리므로 사용을
하지 말자 (2012. 1)
iOS 계열에서 canvas 사용시 성능 향상 tip
¤ 

Retina display를 사용하는 iOS에서 CSS의 하나의 pixel은 실질적으로 display
의 두 pixel을 의미
n 

iOS 내부적으로 app에게는 320 pixel width로 rendering을 하게하나 이를 2배로 scal
ing 하는 기능을 내포하고 있음: CPU를 통한 rescale로 늦은 것으로 예측됨

¤ 

이를 역이용하여 viewport의 initial_scale를 0.5로 하여 원래 content를 작게 축
소하여 rendering을 하게 하고 이를 -webkit-transform: scale3d(2, 2, 0)로 2배
로 늘리는 방식이 더 높은 성능을 보여줌: GPU를 통한 rescaling

¤ 

http://29a.ch/2011/5/27/fast-html5-canvas-on-iphone-mobile-safari-perfo
rmance
DOM 관련 최적화
106

¨ 
¨ 
¨ 
¨ 

¨ 

¨ 

[RULE] 페이지 복잡도를 낮추어 DOM 노드의 개수를 최소화 하라
[RULE] DOM lookup 결과는 cache 하여 재사용 하라
[RULE] DOM을 manipulation하는 것을 최소화 하라
Event propagation, reflow, repaint등의 모든 연산시 DOM 노드의 개수에 비례하여
delay가 증가하게 된다
Page에 DOM node의 개수를 알려주는 tool
¤  DOM Monster 사용:http://mir.aculo.us/dom-monster/
¤  http://stevesouders.com/mobileperf/pageresources.php

DOM 개수를 줄이는 tip
¤ 

구체적인 사례 분석을 통해서 추가해야함
DOM manipulation 최적화
107

¨ 

¨ 

[RULE] DOM을 manipulation 연산은 최소화하거나, 대상이 되는 DOM은
DOM tree에서 detach해서 변경하라
DOM 재활용 예제
¤ 
¤ 
¤ 
¤ 
¤ 
¤ 

¨ 

Pool Elements and Objects
Reuse instead of Allocate and Destroy
Create a pool of DOM elements (more than you need)
Use the nodes you created
Release back into pool, then Go to step 2
http://www.standardista.com/velocity/#slide51

DOM manipulation 비용 최소화 방법
¤ 
¤ 
¤ 
¤ 

임시적인 변경은 documentFragment 로 보관
Update할 DOM node는 clone을 하고, 변경후에 copy하고 swap하는 방식
display:none (1 reflow, repaint)으로 제거하고, 변경을 수행, 그리고 display를 하는
방식으로 2 reflows 만 발생하게함
http://www.phpied.com/rendering-repaint-reflowrelayout-restyle/
FE 성능 개선 Guide – Part 3
108

¨ 

JavaScript
JavaScript Engine 특징
109

¨ 

V8 엔진 (Google Chrome and Android 2.3 higher)
¤ 
¤ 
¤ 

JavaScript à Machine Code (not a JIT, a compiler)
Garbage collector: generational stop-the-world
Crankshaft (Chrome Canary build only, ARM version under 개발)
n 
n 
n 
n 

¨ 

Base compiler: minimal한 최적화로 빠르게 코드 생성
Runtime profiler: 수행시간 지연 monitoring
Optimizing compiler: advanced 최적화 기술 적용 및 코드 생성
Deoptimization support:

SFX 엔진 (Apple iOS)
¤ 
¤ 

JavaScript à Bytecode à Machine Code (JIT)
JIT는 Browser에서만 동작
n 

¤ 

생성된 Native code는 Apple사에 의한 signing이 필수이나 browser에서만 예외 처리

WebView에서는 미동작: Hybrid app에서는 보안 이슈로 미지원 (추정)
JavaScript Loading Sequence
110

¨ 

Web browser가 Document object를 생성하고 parsing을 개시
¤ 
¤ 

¨ 

Element와 Text Node를 document에 추가
Document.readyState는 “loading”로 set

Tag parsing 계속
¤ 

“async”나 “defer” attribute를 갖지 않는 <script> tag를 만나면
n 
n 

¤ 

“async”나 attribute를 갖는 <script> tag를 만나면
n 
n 

¨ 

element를 삽입하고 synchronous하게 실행함
Download하고 실행시까지 parsing은 stop and wait
Download를 개시하고 parsing 계속
해당 script가 도착할때마다 실행하고 순서는 지켜지지 않음

Tag parsing 완료시
¤ 
¤ 

readyState는 “intractive”로 set
“defer” attribute가 set된 모든 <script>를 순차적으로 실행

JavaScript: The Definitive Guide
JavaScript Loading Sequence
111

¨ 

Parsing을 완료후 DOMContentLoaded event를 fire
¤ 

¤ 

¨ 

이 시점에 “async” attribute로 set된 script block이 여전히 실행되지 않고 있을
수 있음
“defer” attribute로 set된 script block은 실행 완료

readyState가 “complete”로 set 됨
¤ 
¤ 

¨ 

모든 resource (image등)의 download가 완료
모든 “async” attribute로 set된 script block의 download 및 실행 완료

User input에 대해 event handler가 asynchronous하게 실행

JavaScript: The Definitive Guide
JavaScript 실행 제약
112

¨ 

¨ 

[RULE] JavaScript의 수행은 main thread의 block을 야기하므로 최대한 짧
게 수행되도록하라
JavaScript 수행동안 UI refresh 가 되지 않음
¤ 
¤ 

¨ 

iOS에서의 JavaScript 실행 제약 조건
¤ 
¤ 

¨ 

Scheduling, preemption, multiplexing 되지 않음
Chrome, WebKit2는 multi-process 도입으로 해당 사항 없음
수행 시간이 5초가 넘어가면 수행 중지
사용하는 Memory가 10MB가 넘어갈 경우 수행 중지

기존의 Task 쪼개기 방식
¤ 
¤ 

setTimeOut, setInterval을 통해 쪼개서 작업
XMLHttpRequest로 asynchronous 하게 처리
Web Worker Thread 사용 (1/2)
113

¨ 

HTML 5의 Web worker thread
¤ 

JavaScript의 Concurrency 제약을 극복하기 위한 HTML 5 기능
Background에서 JavaScript를 수행하게 하고, message passing mechanis
m을 제공함

¤ 

Worker thread는 DOM 접근이 되지 않고 message posting만 사용 해야함

¤ 

¨ 

Web worker 사용예
Main
var worker = new Worker('doWork.js'); // worker 생성, 별도 file로 수행할 JS 파일 contain
worker.addEventListener('message', function(e) { console.log('Worker said: ', e.data); }, false);
worker.postMessage('Hello World'); // start by sending data to our worker.
doWork.js
self.addEventListener('message', function(e) {
self.postMessage(e.data);
}, false);

http://www.whatwg.org/specs/web-apps/current-work/multipage/workers.html
Web Worker Thread 사용 (2/2)
114

¨ 

Web worker thread는 multi-threaded 특징 때문에 JavaScript 기
능의 subset 만을 접근 가능함
¤ 

접근 가능
n 
n 
n 
n 
n 
n 

¤ 

Navigator object 접근 가능
Location object read-only로 접근 가능
XMLHttpRequest 사용 가능
setTimeout/clearTimeout(), setInterval/clearInterval()
External script를 importScripts()로 import
또 다른 web worker thread 생성

접근 불가능
n 
n 
n 
n 

DOM access
Window object
Document object
Parent object

http://www.html5rocks.com/en/tutorials/workers/basics/
JavaScript Timer 동작
115

¨ 

[RULE] SetTimeout 와 setInterval의 동작의 차이점을 이해하고 사용
하라.
¤ 
¤ 

JavaScript code는 one piece of code at a time으로 실행
미실행 Asynchronous JavaScript event queue에 쌓이고 sequential 하게 수
행됨
requestAnimationFrame (1/2)
116

¨ 

¨ 

[RULE] JavaScript로 animation을 하고자 할 경우 timer를 사용하지
말고 requestAnimationFrame을 사용하라
WebKit 엔진 및 Native Platform의 Rendering 시스템상에서 최적의
animation frame 생성 시점 도달시 제공된 API에 의해 등록된 Callba
ck을 호출
¤ 

Mobile OS 별로 화면 갱신 방식의 차이가 있음
n 
n 
n 

¨ 

vsync를 사용하는 system은 실제 LCD screen buffer로의 복사 frequency가 해당값
에 제약 받음
vsync 60 fps system은 JavaScript 수준 animation에서 그것을 초과하는 frame rat
e을 구현할수 없음
e.g.) 60 fps시스템 à 60/sec로 호출 best effort, not guaranteed

지원 시스템
¤ 
¤ 

Safari, Chrome, Firefox
Mobile에서는 도입 예정
requestAnimationFrame (2/2)
117

¨ 

사용시 장점
¤ 

동시에 발생하는 각종 animation을 browser 수준에서 최적화 할수 있음
n 
n 

¤ 

JS animation과 CSS transition을 synchronize 가능함
e.g.) 한번의 reflow나 repaint로 화면을 최종 화면을 구성

Invisible한tab에 위치한 animation은 호출 되지 않음
n 

¨ 

CPU, GPU 사용 및 메모리 사용을 줄여 battery 효율적인 동작이 가능함

사용 예제 https://gist.github.com/1579671
// shim layer with setTimeout fallback window.requestAnimFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function( callback ){ window.setTimeout(callback, 1000 / 60); }; })();
// usage:
// instead of setInterval(render, 16) ....
(function animloop(){ requestAnimFrame(animloop);
render();
})();
// place the rAF *before* the render() to assure as close to
// 60fps with the setTimeout fallback.
CSS property 접근
118

¨ 

[RULE] JavaScript를 통한 CSS Property의 접근은 page loading
이 완료된 시점에서 하자.
¤ 

¨ 

E.g. onload event후

Page loading 중 CSS property 접근시 문제점
¤ 

JavaScript를 통한 CSS property의 접근은 WebKit에서 가장 비싼 연산인 layo
ut() 강제함: 수백 msec도 소요 가능성 있음

¤ 

WebKit 엔진: Pending되어있는 CSS stylesheet를 무시하고 layout후에 해당
값을 돌려준다

¤ 

기타 Browser: CSS가 완전히 loading 될때까지 JavaScript를 suspension 시
키거나
// FIXME: This is a bad idea and needs to be removed eventually.
// Other browsers load stylesheets before they continue parsing the web page.
// Since we don't, we can run JavaScript code that needs answers before the
// stylesheets are loaded. Doing a layout ignoring the pending stylesheets
// lets us get reasonable answers. The long term solution to this problem is
// to instead suspend JavaScript execution.
void Document::updateLayoutIgnorePendingStylesheets()
{

CSS property 접근시 수행되는 WebKit 내부 함수
JavaScript loading 최적화 (1/6)
119

¨ 

¨ 

[RULE] HTML 문서 적재 시점까지 호출되지 않는 JavaScript function의 lo
ading은 미루자
Script 수행 철칙: 어길 시 수행 결과의 correctness를 깨트림
¤ 
¤ 

¨ 

“Script Execute In Order”
“Script Execute after fully loading all stylesheets”

JavaScript loading 방식: <script src =“file.js”> 및 inline JavaScript는 H
TML parsing, page rendering을 block 시킴
¤ 

HTML parsing 도중 inline 또는 external JavaScript를 만나면
n 
n 

¤ 

Inline JavaScript는 parsing후 호출이 되었으면 실행
External JavaScript는 network을 통해 적재, parsing후 호출이 되었으면 실행

Loading,parsing, 실행중 계속적인 HTML parsing은 suspend가 기본 동작
n 

Webkit에서는 속도 향상을 위해 image object는 speculative하게 loading을 수행
n 

¤ 

https://bugs.webkit.org/show_bug.cgi?id=17480 (WebKit PreloadScanner)

이는 JavaScript의 수행으로 DOM 변경이 가능하므로 JavaScript의 수행 완료가 보
장되어야만 하기 때문임
JavaScript loading 최적화 (2/6)
120

¨ 

JavaScript의 loading에 의한 suspend를 최소화 하는 것이 전체 pag
e loading 성능 개선이 필수적임
¤ 

¨ 

Deferring 방법
¤ 
¤ 
¤ 

¨ 

Page startup 동안 꼭 필요한 JavaScript를 제외하고, page startup 이후로 def
erring
“defer” attribute 정의
“async” attribute 정의
JavaScript 실행이 필요한 시점이 되서야 load 되도록 program 작성

Deferring 장점
¤ 
¤ 
¤ 

초기 download size 줄어듦
다른 resource (image, CSS)가 병렬로 load 가능
Startup 시점까지 꼭 필요한 JavaScript만이 load되고 compile되어서, 궁극적으
로 rendering time 빨라짐
JavaScript loading 최적화 (3/6)
121

¨ 

defer attribute 사용
¤ 

¨ 

async attribute 사용
¤ 

¨ 

<script defer src="siteScript.js" onload="myInit()"></script>

async 와 defer의 공통점
¤ 
¤ 

¨ 

<script src="script.js" type="text/javascript" defer="defer"></script>

Parser를 멈추지 않고 해당 script download를 즉시 시작함
Optional onload handler에서 initialization 수행

async 와 defer의 차이점
¤ 
¤ 

async는 download가 끝나는 시점과 window load event 전에 실행됨
defer는 async와 동일하나 defer된 순서를 지켜서 수행하고 parsing이 끝나는 시점에서 DOM
ContentLoaded event 발생전까지 수행됨
n 

DOMContentLoaded
n 
n 

n 

Window load
n 

¨ 

해당 page의 document parsing이 완료되고, 즉 DOM tree 가 완성시 fire
Referenced stylesheet, image, subframe 적재는 안끝날수도 있음
Subresource까지의 loading이 끝났을때 발생

두개 모두 지정시: async attribute 특성으로만 동작

http://davidwalsh.name/html5-async
JavaScript loading 최적화 (4/6)
122

¨ 

Programmer driven 최적화
¤ 

¨ 

JavaScript module 화
¤ 

¨ 

JavaScript의 module 화 및 lazy loading
기능 block 별로분리하고 onload 전과 후, 그리고 실제 호출 시점에 loading 가능하도
록함

Lazy loading 적용 사례
¤ 

Script as DOM
<script type="text/JavaScript">
function loadFile(url) {
var script = document.createElement('SCRIPT');
script.src = url;
document.getElementsByTagName('HEAD')[0].appendChild(script);
}
</script>

¤ 
¤ 

XmlHttpRequest (XHR)
/* */ comment block안에 JS를 넣어두면 network loading은 하나 parsing은 하지
않는다. 후에 unstrip을 하고 eval을 통해서 parsing함
n 

http://googlecode.blogspot.com/2009/09/gmail-for-mobile-html5-series-reducing.ht
ml
JavaScript loading 최적화 (5/6)
123

¨ 

WebKit이 HTMLDocumentParser의 동작
¤ 

external script의 download, 실행 완료까지 HTMLDocumentParser가 block
n 

¤ 

¨ 

Block에 의한 page loading 및 rendering 속도 저하 심각

WebKit PreloadScanner
¤ 

HTMLDocumentParser가 block 되는 동안 미리 download 가능한 subresour
ce (CSS, JS)가 있는지를 speculatively하게 scan 하여 download 개시
n 

¨ 

CSS나 기타 resource는 HTMLDocumentParser를 block 시키지 않음

https://bugs.webkit.org/show_bug.cgi?id=17480 (WebKit PreloadScanner)

PreloadScanner 동작 조건 (Browser 별로 실험 필요)
¤ 

<head>내에 defer, async가 없을 경우 <body>내의 script 를 preload

http://gent.ilcore.com/2011/01/webkit-preloadscanner.html
JavaScript loading 최적화 (6/6)
124

¨ 

PreloadScanner의 제약사항
¤ 

Scanning 되지 않는 subresource
n 

¤ 
¤ 
¤ 

¤ 

iframe, @import stylesheet, fonts, HTML5 audio/video,

<head>에서 block 되면 <body>는 scan 하지 않음
<xhtml>에서 미동작
PreloadScanner에서 생성한 token을 HTMLDocumentParser에서 재활용하
지 않음
External stylesheet는 완전히 download 되기 전까지 scan 되지 않음

http://gent.ilcore.com/2011/01/webkit-preloadscanner.html
document.write() 사용 제한
125

¨ 
¨ 

[RULE] 필요한 resource는 HTML markup 으로 직접 정의하라
아래와 같이 loading시 document.write를 부른 js와 second.js가 모
두 loading 될 때까지 blocking 됨
document.write('<script src="second.js"></script>');

http://www.whatwg.org/specs/web-apps/current-work/multipage/parsing.html
CSS @import 제약사항
126

¨ 

¨ 

[RULE] <link> tag를 사용하여 CSS를 load하고 CSS @import를
사용하지 말아라
Browser는 일반적으로 import 된 stylesheet을 병렬 loading을 지원
하지 않음
Third party script 통합
127

¨ 

[RULE] Third party script의 loading은 async로 설정하여 onload
이후에 load 및 실행하도록 하자
¤ 

</body> 직전에 삽입도 가능

¨ 

Top e-commerce site는 평균 7개를 포함하고, 25개까지 포함

¨ 

Popular third party JS
¤ 
¤ 
¤ 
¤ 
¤ 

Facebook Like button
Google Plus button (http://www.google.com/webmasters/+1/button/)
Twitter Share & Follow button (they require the same JS file)
Twitter Tweet Box
Google Analytics
n 

GA는 async로 설정하는 field를 제공함

http://www.aaronpeters.nl/blog/why-loading-third-party-scripts-async-is-not-good-enough
FE 성능 개선 Guide – Part 4
128

¨ 

DOM Event
DOM Event 지원 및 호환성
129

¨ 

Mobile browser compatibility 이슈
¤ 

¨ 

Mouse가 없는 Touch Screen 장치의 특징 때문에 User Interaction과 관련이 있는
DOM event들의 호환성의 차이가 mobile OS 별로 발생

Major difference
¤ 

Mouse 부재에 따른 mouse event emulation
n 

Mouse event 자체, 이와 연관되 form/document 이벤트 동작 호환성 상이
n 

¤ 

mousemove, mouseout, :hover, blur, focus 등

Touch 전용 event 정의
n 

iOS에서는 native 및 JavaScript에서 사용 가능하도록 통일하여 지원중
n 

n 

n 

iOS UIEvent
n  http://developer.apple.com/library/safari/#documentation/UserExperience/Refere
nce/TouchEventClassReference/TouchEvent/TouchEvent.html
iOS Safari JavaScript Object
n  http://developer.apple.com/library/IOs/#documentation/AppleApplications/Refere
nce/SafariWebContent/HandlingEvents/HandlingEvents.html#//apple_ref/doc/uid/
TP40006511-SW1

현재 널리 채택되어 사용되고 있음
iOS User Interaction Guide
130

¨ 

Browser vendor 및 Platform 별로 호환성이 차이 분석
¤ 

iOS상 click 동작: clickable element에서의 click시 아래의 순서로 발생
n 
n 

¤ 

mouseoveràmousemoveàmousedownàmouseupàclick
mouseout: clickable에서 click후 다른 clickable element를 click할 때만 발생

iOS상 scroll 동작
n 

Pan 동작 완료 시점에 1회 발생
iOS 지원 Event 현황
131
Event
abort
blur
change
click
copy
cut
drag
drop
focus
gesturestart
gesturechange
gestureend
load
mousemove
mousedown
mouseup
mouseover
mouseout
orientationchange
pagehide
pageshow
paste
reset
selection
submit
touchcancel
touchend
touchmove
touchstart
unload

Generated
Yes
Yes
Yes
Yes
No
No
No
No
Yes
Yes
Yes
Yes
Yes
Yes
Yes
Yes
Yes
Yes
Yes
Yes
Yes
No
Yes
No
Yes
Yes
Yes
Yes
Yes
Yes

Conditional
No
No
No
Yes
N/A
N/A
N/A
N/A
No
N/A
N/A
N/A
No
Yes
Yes
Yes
Yes
Yes
N/A
No
No
N/A
No
N/A
No
N/A
N/A
N/A
N/A
No

Available
iOS 1.0 and later.
iOS 1.0 and later.
iOS 1.0 and later.
iOS 1.0 and later.

iOS 1.0 and later.
iOS 2.0 and later.
iOS 2.0 and later.
iOS 2.0 and later.
iOS 1.0 and later.
iOS 1.0 and later.
iOS 1.0 and later.
iOS 1.0 and later.
iOS 1.0 and later.
iOS 1.0 and later.
iOS 1.1.1 and later.
iOS 4.0 and later.
iOS 4.0 and later.
iOS 1.0 and later.
iOS 1.0 and later.
iOS 2.0 and later.
iOS 2.0 and later.
iOS 2.0 and later.
iOS 2.0 and later.
iOS 1.0 and later.

http://developer.apple.com/library/IOs/#documentation/AppleApplications/Reference/SafariWebContent/HandlingEvents/HandlingEvents.html#//apple_ref/doc/uid/TP40006511-SW1
Touch event
132

¨ 

¨ 

[RULE] touch screen device에서 사용자 touch에 의한 content의 p
anning은 touch event를 사용하라
Mouse/wheel event 사용시 conflict 발생 가능
¤ 

¨ 

Bluetooth mouse가 touch screen과 같이 쓰이는 configuration에서 그것들을
구분하여 처리할 수 있음

Apple이 제안한 touch event
touchstart: Happens every time a finger is placed on the screen
touchend: Happens every time a finger is removed from the screen
touchmove: Happens as a finger already placed on the screen is moved across the screen
touchcancel: The system can cancel events,
node.ontouchstart = function(evt){
console.log(evt.pageX + "/" + evt.pageY);
// OH NO! These values are blank, this must be a bug
}
Event 사용 제약
133

¨ 

¨ 

[RULE] DOM Level 2의 mouse event는 지원 여부 및 동작 방식을
Platform별로 확인 후 사용
[RULE] onclick 이벤트의 경우 생성시 300-500msec delay가 발생
가능하므로 즉시 발생이 필요한 경우 touch event를 사용하라
¤ 

¨ 

데모 동작 확인: http://pcapperf.appspot.com/fastbutton

[RULE] onscroll은 1회만 발생하므로 desktop에서의 mousemove
와 같은 연산의 ontouchmove (touch event)를 사용하라
Fast button 제작
134

¨ 

¨ 

browser의 onclick event는 double tap/panning 등의 처리로 지연 (
e.g. 300msec iOS)를 포함하고 이는 game에서와 같이 빠른 respon
se를 필요로 하는 web app 개발시 제약임
onTouchStart는 지연없이 동작
¤ 

<div ontouchStart=“doSomething()”> 구성 가능하나 누르는 순간 발생

¤ 

onTouchEnd에서 발생시켜서 onclick을 emulation

http://cubiq.org/remove-onclick-delay-on-webkit-for-iphone
http://code.google.com/intl/ko-KR/mobile/articles/fast_buttons.html
Touch 기반 Fast Button 예제 1
135

function NoClickDelay(el) {
this.element = typeof el == 'object' ? el : document.getElementById(el);
if( window.Touch ) this.element.addEventListener('touchstart', this, false);
} NoClickDelay.prototype = { handleEvent: function(e) {
switch(e.type) {
case 'touchstart': this.onTouchStart(e); break;
case 'touchmove': this.onTouchMove(e); break;
case 'touchend': this.onTouchEnd(e); break; } },
onTouchStart: function(e) {
e.preventDefault(); this.moved = false;
this.theTarget = document.elementFromPoint(e.targetTouches[0].clientX, e.targetTouches[0].clientY);
if(this.theTarget.nodeType == 3) this.theTarget = theTarget.parentNode;
this.theTarget.className+= ' pressed';
this.element.addEventListener('touchmove', this, false);
this.element.addEventListener('touchend', this, false); },
onTouchMove: function(e) {
this.moved = true; this.theTarget.className = this.theTarget.className.replace(/ ?pressed/gi, ''); },
onTouchEnd: function(e) {
this.element.removeEventListener('touchmove', this, false);
this.element.removeEventListener('touchend', this, false);
if( !this.moved && this.theTarget ) { this.theTarget.className = this.theTarget.className.replace(/ ?pressed/gi, '');
var theEvent = document.createEvent('MouseEvents');
theEvent.initEvent('click', true, true);
this.theTarget.dispatchEvent(theEvent);
} this.theTarget = undefined;
} };
Google Clickbuster
136

google.ui.FastButton = function(element, handler) {
this.element = element;
this.handler = handler;
element.addEventListener('touchstart', this, false);
element.addEventListener('click', this, false);
};
google.ui.FastButton.prototype.handleEvent = function(event) {
switch (event.type) {
case 'touchstart': this.onTouchStart(event); break;
case 'touchmove': this.onTouchMove(event); break;
case 'touchend': this.onClick(event); break;
case 'click': this.onClick(event); break;
}
};
google.ui.FastButton.prototype.onTouchStart = function(event) {
event.stopPropagation();
this.element.addEventListener('touchend', this, false);
document.body.addEventListener('touchmove', this, false);
this.startX = event.touches[0].clientX;
this.startY = event.touches[0].clientY;
};
google.ui.FastButton.prototype.onTouchMove = function(event) {
if (Math.abs(event.touches[0].clientX - this.startX) > 10 ||
Math.abs(event.touches[0].clientY - this.startY) > 10) {
this.reset();
}
};

google.ui.FastButton.prototype.onClick = function(event) {
event.stopPropagation();
this.reset();
this.handler(event);
if (event.type == 'touchend') {
google.clickbuster.preventGhostClick(this.startX, this.startY);
}
};
google.ui.FastButton.prototype.reset = function() {
this.element.removeEventListener('touchend', this, false);
document.body.removeEventListener('touchmove', this, false);
};
google.clickbuster.preventGhostClick = function(x, y) {
google.clickbuster.coordinates.push(x, y);
window.setTimeout(google.clickbuster.pop, 2500);
};
google.clickbuster.pop = function() {
google.clickbuster.coordinates.splice(0, 2);
};
google.clickbuster.onClick = function(event) {
for (var i = 0; i < google.clickbuster.coordinates.length; i += 2) {
var x = google.clickbuster.coordinates[i];
var y = google.clickbuster.coordinates[i + 1];
if (Math.abs(event.clientX - x) < 25 && Math.abs(event.clientY - y) < 25) {
event.stopPropagation();
event.preventDefault();
}
}
};
document.addEventListener('click', google.clickbuster.onClick, true);
google.clickbuster.coordinates = [];
Double tap 대응
137

¨ 

¨ 

[RULE] double tap시 browser 별 동작 조건을 고려해서 object를 배
치 하자
iOS상 double tap for zooming
¤ 

¨ 

Android상 double tap for zooming
¤ 

¨ 

<div>, <ol>, <ul>, <table>, <img> element를 찾고 해당 element가 block일
경우 content를 화면 크기에 fitting 시키고 중앙으로 이동
Double tap 된 부분을 기준으로 특정 zoom level로 확대나 축소

Samsung Android 상 double tap for column zooming
¤ 

<p> <article>등의 block 일 경우 device width로 content를 layout하여 displa
y 해줌
FE 성능 개선 Guide – Part 5
138

¨ 

Networking/Caching/Loading
DNS Prefetch
139

¨ 
¨ 

[RULE] 명시적으로 이동할 link는 DNS prefetch 를 사용하라
Chrome Browser 지원
<link rel="prefetch" href="http://www.example.com/">
LocalStorage 사용
140

¨ 

¨ 
¨ 

[RULE] 변경이 자주 되지 않은 content는 client-side cache에 저장
되도록 하거나, localStorage에 명시적으로 저장하여 network reques
t 발생 최소화 하자
http://dev.w3.org/html5/webstorage/
google.com 활용 예
¤ 

JavaScript와 CSS를 저장후 재방문시 사용: 130 entry로 저장
mres.-8Y5Dw_nSfQztyYx: <style>a{color:#11c}a:visited{color:#551a8b}body{margin:0;pad...
mres.-Kx7q38gfNkQMtpx: <script> //<![CDATA[ var Zn={},bo=function(a,b){b&&Zn[b]||(ne...
mres.0kH3gDiUpLA5DKWN: <style>.zl9fhd{padding:5px 0 0}.sc59bg{clear:both}.pyp56b{tex...
mres.0thHLIQNAKnhcwR4: <style>.fdwkxt{width:49px;height:9px;background:url("data:ima...
mres.36ZFOahhhEK4t3WE: <script> //<![CDATA[ var kk,U,lk;(function(){var a={};U=funct...
mres.3lEpts5kTxnI2I5S: <script> //<![CDATA[ var Ec,Fc,Gc=function(a){this.Jl=a},Hc="...
mres.4fbdvu9mdAaBINjE: <script> //<![CDATA[ u("_clOnSbt",function(){var a=document.g...
mres.5QIb-AahnDgEGlYP: <script> //<![CDATA[ var cb=function(a){this.Cc=a},db=/s*;s...
mres:time.-8Y5Dw_nSfQ...: 1301368541872
mres:time.-Kx7q38gfNk...: 1301368542755
mres:time.0kH3gDiUpLA...: 1301368542257
mres:time.0thHLIQNAKn...: 1301368542223
mres:time.36ZFOahhhEK...: 1301368542635
mres:time.3lEpts5kTxn...: 1301368542579
mres:time.4fbdvu9mdAa...: 1301368542720
mres:time.5QIb-AahnDg...: 1301368542856

http://calendar.perfplanet.com/2011/localstorage-read-performance/
RTT 최소화
141

¨ 

[RULE] external CSS나 external JS 파일은 수를 최소화 하라
[RULE] image는 CSS Sprite로 파일의 수를 줄여라

¨ 

CSS Sprite 서비스

¨ 

¤ 

¤ 

¨ 

Image중 항상 같이 load 되거나, 동적으로 변경되지 않은 것을 한 개의 image로
묶음
http://spriteme.org/

Sprite한 image의 format이 JPEG일 경우 sub-sampling에 의한 im
age 왜곡이 심각하게 발생할 수 있으니 최대 size를 넘지 않도록 정해야
함
¤ 

iOS는 2MB
CSS와 JS 파일 Ordering 최적화
142

¨ 
¨ 
¨ 

[RULE] external CSS는 가능하면 external JS 이전에 배치하라
[RULE] inline script는 가능하면 외부 자원이후에 배치하라
JavaScript는 DOM을 변경가능하므로 JavaScript를 만나면 downlo
ad해서 실행할 때까지 다른 자원의 parallel loading을 block함
Combine external JavaScript
143

¨ 
¨ 

[RULE] external JavaScript의 수를 줄여라
[RULE] JavaScript는 기능 단위 module 분리하고 실행하라
¤ 

¤ 
¤ 

<head>내의 JavaScript file의 수를 최소화 하라
잘 방문하지 않는 site의 JavaScript는 해당 page가 열릴때만 download 받게 하
라

¤ 

¨ 

Page startup에 필요한 minimal code와 page load후에 필요한 부분 두개로 나
누어라

작은 양의 JavaScript code는 HTML에 inlining 하는 것을 고려하라

즉, page load 전과 후에 필요한 큰 file 두개로 나누어서 관리 하도록
하자
The comprehensive guide for optimizing the performance of mobile HTML5 Web applications
The comprehensive guide for optimizing the performance of mobile HTML5 Web applications
The comprehensive guide for optimizing the performance of mobile HTML5 Web applications
The comprehensive guide for optimizing the performance of mobile HTML5 Web applications
The comprehensive guide for optimizing the performance of mobile HTML5 Web applications
The comprehensive guide for optimizing the performance of mobile HTML5 Web applications
The comprehensive guide for optimizing the performance of mobile HTML5 Web applications
The comprehensive guide for optimizing the performance of mobile HTML5 Web applications
The comprehensive guide for optimizing the performance of mobile HTML5 Web applications
The comprehensive guide for optimizing the performance of mobile HTML5 Web applications
The comprehensive guide for optimizing the performance of mobile HTML5 Web applications
The comprehensive guide for optimizing the performance of mobile HTML5 Web applications
The comprehensive guide for optimizing the performance of mobile HTML5 Web applications
The comprehensive guide for optimizing the performance of mobile HTML5 Web applications
The comprehensive guide for optimizing the performance of mobile HTML5 Web applications
The comprehensive guide for optimizing the performance of mobile HTML5 Web applications
The comprehensive guide for optimizing the performance of mobile HTML5 Web applications
The comprehensive guide for optimizing the performance of mobile HTML5 Web applications
The comprehensive guide for optimizing the performance of mobile HTML5 Web applications
The comprehensive guide for optimizing the performance of mobile HTML5 Web applications
The comprehensive guide for optimizing the performance of mobile HTML5 Web applications
The comprehensive guide for optimizing the performance of mobile HTML5 Web applications
The comprehensive guide for optimizing the performance of mobile HTML5 Web applications
The comprehensive guide for optimizing the performance of mobile HTML5 Web applications
The comprehensive guide for optimizing the performance of mobile HTML5 Web applications
The comprehensive guide for optimizing the performance of mobile HTML5 Web applications
The comprehensive guide for optimizing the performance of mobile HTML5 Web applications
The comprehensive guide for optimizing the performance of mobile HTML5 Web applications
The comprehensive guide for optimizing the performance of mobile HTML5 Web applications
The comprehensive guide for optimizing the performance of mobile HTML5 Web applications
The comprehensive guide for optimizing the performance of mobile HTML5 Web applications
The comprehensive guide for optimizing the performance of mobile HTML5 Web applications
The comprehensive guide for optimizing the performance of mobile HTML5 Web applications
The comprehensive guide for optimizing the performance of mobile HTML5 Web applications
The comprehensive guide for optimizing the performance of mobile HTML5 Web applications
The comprehensive guide for optimizing the performance of mobile HTML5 Web applications
The comprehensive guide for optimizing the performance of mobile HTML5 Web applications
The comprehensive guide for optimizing the performance of mobile HTML5 Web applications
The comprehensive guide for optimizing the performance of mobile HTML5 Web applications
The comprehensive guide for optimizing the performance of mobile HTML5 Web applications
The comprehensive guide for optimizing the performance of mobile HTML5 Web applications
The comprehensive guide for optimizing the performance of mobile HTML5 Web applications
The comprehensive guide for optimizing the performance of mobile HTML5 Web applications
The comprehensive guide for optimizing the performance of mobile HTML5 Web applications
The comprehensive guide for optimizing the performance of mobile HTML5 Web applications
The comprehensive guide for optimizing the performance of mobile HTML5 Web applications
The comprehensive guide for optimizing the performance of mobile HTML5 Web applications
The comprehensive guide for optimizing the performance of mobile HTML5 Web applications
The comprehensive guide for optimizing the performance of mobile HTML5 Web applications
The comprehensive guide for optimizing the performance of mobile HTML5 Web applications
The comprehensive guide for optimizing the performance of mobile HTML5 Web applications
The comprehensive guide for optimizing the performance of mobile HTML5 Web applications
The comprehensive guide for optimizing the performance of mobile HTML5 Web applications
The comprehensive guide for optimizing the performance of mobile HTML5 Web applications
The comprehensive guide for optimizing the performance of mobile HTML5 Web applications
The comprehensive guide for optimizing the performance of mobile HTML5 Web applications
The comprehensive guide for optimizing the performance of mobile HTML5 Web applications
The comprehensive guide for optimizing the performance of mobile HTML5 Web applications
The comprehensive guide for optimizing the performance of mobile HTML5 Web applications
The comprehensive guide for optimizing the performance of mobile HTML5 Web applications
The comprehensive guide for optimizing the performance of mobile HTML5 Web applications
The comprehensive guide for optimizing the performance of mobile HTML5 Web applications
The comprehensive guide for optimizing the performance of mobile HTML5 Web applications
The comprehensive guide for optimizing the performance of mobile HTML5 Web applications
The comprehensive guide for optimizing the performance of mobile HTML5 Web applications
The comprehensive guide for optimizing the performance of mobile HTML5 Web applications
The comprehensive guide for optimizing the performance of mobile HTML5 Web applications
The comprehensive guide for optimizing the performance of mobile HTML5 Web applications

Contenu connexe

Tendances

Angularjs, ionic, cordova 기반 syrup store app 개발 사례 공유
Angularjs, ionic, cordova 기반 syrup store app 개발 사례 공유Angularjs, ionic, cordova 기반 syrup store app 개발 사례 공유
Angularjs, ionic, cordova 기반 syrup store app 개발 사례 공유Sang Seok Lim
 
하이브리드 앱_개발_개요
하이브리드 앱_개발_개요하이브리드 앱_개발_개요
하이브리드 앱_개발_개요BongSoo Jang
 
모바일웹Ui개발 저자세미나 0부
모바일웹Ui개발 저자세미나 0부모바일웹Ui개발 저자세미나 0부
모바일웹Ui개발 저자세미나 0부NAVER D2
 
[D2 오픈세미나]1.html5 api 옥상훈
[D2 오픈세미나]1.html5 api 옥상훈[D2 오픈세미나]1.html5 api 옥상훈
[D2 오픈세미나]1.html5 api 옥상훈NAVER D2
 
캠프앱 개발 사례를 통해 본 하이브리드앱 어디까지 | Devon 2012
캠프앱 개발 사례를 통해 본 하이브리드앱 어디까지 | Devon 2012캠프앱 개발 사례를 통해 본 하이브리드앱 어디까지 | Devon 2012
캠프앱 개발 사례를 통해 본 하이브리드앱 어디까지 | Devon 2012Daum DNA
 
오늘 당장 시작하는 HTML5
오늘 당장 시작하는 HTML5오늘 당장 시작하는 HTML5
오늘 당장 시작하는 HTML5Taegon Kim
 
[D2 오픈세미나]1.무한스크롤성능개선
[D2 오픈세미나]1.무한스크롤성능개선[D2 오픈세미나]1.무한스크롤성능개선
[D2 오픈세미나]1.무한스크롤성능개선NAVER D2
 
[D2 오픈세미나]3.web view hybridapp
[D2 오픈세미나]3.web view hybridapp[D2 오픈세미나]3.web view hybridapp
[D2 오픈세미나]3.web view hybridappNAVER D2
 
HTML5 플랫폼 동향과 기업업무 적용 방안
HTML5 플랫폼 동향과 기업업무 적용 방안HTML5 플랫폼 동향과 기업업무 적용 방안
HTML5 플랫폼 동향과 기업업무 적용 방안욱래 김
 
차세대 웹 플랫폼과 HTML5 기술 동향
차세대 웹 플랫폼과 HTML5 기술 동향차세대 웹 플랫폼과 HTML5 기술 동향
차세대 웹 플랫폼과 HTML5 기술 동향Jonathan Jeon
 
프로그레시브 웹앱(Pwa)
프로그레시브 웹앱(Pwa)프로그레시브 웹앱(Pwa)
프로그레시브 웹앱(Pwa)Woncheol Lee
 
반응형 웹 기술 이해 V.2
반응형 웹 기술 이해 V.2반응형 웹 기술 이해 V.2
반응형 웹 기술 이해 V.2Lee Ji Eun
 
하이브리드앱 성능 극복
하이브리드앱 성능 극복하이브리드앱 성능 극복
하이브리드앱 성능 극복sung hwan Park
 
[D2 오픈세미나]4.진보된개발환경 주우영
[D2 오픈세미나]4.진보된개발환경 주우영[D2 오픈세미나]4.진보된개발환경 주우영
[D2 오픈세미나]4.진보된개발환경 주우영NAVER D2
 
W3C Automotive 표준 개발 현황
W3C Automotive 표준 개발 현황W3C Automotive 표준 개발 현황
W3C Automotive 표준 개발 현황Wonsuk Lee
 
하이브리드 앱 개발 개요
하이브리드 앱 개발 개요하이브리드 앱 개발 개요
하이브리드 앱 개발 개요Sohee Jeong
 
JavaScript MEAN 스택
JavaScript MEAN 스택JavaScript MEAN 스택
JavaScript MEAN 스택Tai Hoon KIM
 
NAVER 오픈세미나 대구 (2014.08.01) - 오픈소스 라이브러리를 활용한 네이티브 어플리케이션의 데이터 저장과 통신
NAVER 오픈세미나 대구 (2014.08.01) - 오픈소스 라이브러리를 활용한 네이티브 어플리케이션의 데이터 저장과 통신NAVER 오픈세미나 대구 (2014.08.01) - 오픈소스 라이브러리를 활용한 네이티브 어플리케이션의 데이터 저장과 통신
NAVER 오픈세미나 대구 (2014.08.01) - 오픈소스 라이브러리를 활용한 네이티브 어플리케이션의 데이터 저장과 통신Sungwoo Choo
 

Tendances (20)

Angularjs, ionic, cordova 기반 syrup store app 개발 사례 공유
Angularjs, ionic, cordova 기반 syrup store app 개발 사례 공유Angularjs, ionic, cordova 기반 syrup store app 개발 사례 공유
Angularjs, ionic, cordova 기반 syrup store app 개발 사례 공유
 
HTML5 와 미래웹기술 part 1
HTML5 와 미래웹기술 part 1HTML5 와 미래웹기술 part 1
HTML5 와 미래웹기술 part 1
 
하이브리드 앱_개발_개요
하이브리드 앱_개발_개요하이브리드 앱_개발_개요
하이브리드 앱_개발_개요
 
모바일웹Ui개발 저자세미나 0부
모바일웹Ui개발 저자세미나 0부모바일웹Ui개발 저자세미나 0부
모바일웹Ui개발 저자세미나 0부
 
[D2 오픈세미나]1.html5 api 옥상훈
[D2 오픈세미나]1.html5 api 옥상훈[D2 오픈세미나]1.html5 api 옥상훈
[D2 오픈세미나]1.html5 api 옥상훈
 
캠프앱 개발 사례를 통해 본 하이브리드앱 어디까지 | Devon 2012
캠프앱 개발 사례를 통해 본 하이브리드앱 어디까지 | Devon 2012캠프앱 개발 사례를 통해 본 하이브리드앱 어디까지 | Devon 2012
캠프앱 개발 사례를 통해 본 하이브리드앱 어디까지 | Devon 2012
 
오늘 당장 시작하는 HTML5
오늘 당장 시작하는 HTML5오늘 당장 시작하는 HTML5
오늘 당장 시작하는 HTML5
 
[D2 오픈세미나]1.무한스크롤성능개선
[D2 오픈세미나]1.무한스크롤성능개선[D2 오픈세미나]1.무한스크롤성능개선
[D2 오픈세미나]1.무한스크롤성능개선
 
[D2 오픈세미나]3.web view hybridapp
[D2 오픈세미나]3.web view hybridapp[D2 오픈세미나]3.web view hybridapp
[D2 오픈세미나]3.web view hybridapp
 
HTML5 플랫폼 동향과 기업업무 적용 방안
HTML5 플랫폼 동향과 기업업무 적용 방안HTML5 플랫폼 동향과 기업업무 적용 방안
HTML5 플랫폼 동향과 기업업무 적용 방안
 
HTML5 와 미래웹기술 part 3
HTML5 와 미래웹기술 part 3HTML5 와 미래웹기술 part 3
HTML5 와 미래웹기술 part 3
 
차세대 웹 플랫폼과 HTML5 기술 동향
차세대 웹 플랫폼과 HTML5 기술 동향차세대 웹 플랫폼과 HTML5 기술 동향
차세대 웹 플랫폼과 HTML5 기술 동향
 
프로그레시브 웹앱(Pwa)
프로그레시브 웹앱(Pwa)프로그레시브 웹앱(Pwa)
프로그레시브 웹앱(Pwa)
 
반응형 웹 기술 이해 V.2
반응형 웹 기술 이해 V.2반응형 웹 기술 이해 V.2
반응형 웹 기술 이해 V.2
 
하이브리드앱 성능 극복
하이브리드앱 성능 극복하이브리드앱 성능 극복
하이브리드앱 성능 극복
 
[D2 오픈세미나]4.진보된개발환경 주우영
[D2 오픈세미나]4.진보된개발환경 주우영[D2 오픈세미나]4.진보된개발환경 주우영
[D2 오픈세미나]4.진보된개발환경 주우영
 
W3C Automotive 표준 개발 현황
W3C Automotive 표준 개발 현황W3C Automotive 표준 개발 현황
W3C Automotive 표준 개발 현황
 
하이브리드 앱 개발 개요
하이브리드 앱 개발 개요하이브리드 앱 개발 개요
하이브리드 앱 개발 개요
 
JavaScript MEAN 스택
JavaScript MEAN 스택JavaScript MEAN 스택
JavaScript MEAN 스택
 
NAVER 오픈세미나 대구 (2014.08.01) - 오픈소스 라이브러리를 활용한 네이티브 어플리케이션의 데이터 저장과 통신
NAVER 오픈세미나 대구 (2014.08.01) - 오픈소스 라이브러리를 활용한 네이티브 어플리케이션의 데이터 저장과 통신NAVER 오픈세미나 대구 (2014.08.01) - 오픈소스 라이브러리를 활용한 네이티브 어플리케이션의 데이터 저장과 통신
NAVER 오픈세미나 대구 (2014.08.01) - 오픈소스 라이브러리를 활용한 네이티브 어플리케이션의 데이터 저장과 통신
 

En vedette

[C1]웹서비스, 빠를수록 좋다
[C1]웹서비스, 빠를수록 좋다[C1]웹서비스, 빠를수록 좋다
[C1]웹서비스, 빠를수록 좋다NAVER D2
 
Korea linuxforum2014 html5game-sangseoklim
Korea linuxforum2014 html5game-sangseoklimKorea linuxforum2014 html5game-sangseoklim
Korea linuxforum2014 html5game-sangseoklimSang Seok Lim
 
레이스 컨디션 기초(Basic Race Condition)
레이스 컨디션 기초(Basic Race Condition)레이스 컨디션 기초(Basic Race Condition)
레이스 컨디션 기초(Basic Race Condition)Sehan Lee
 
웹 애플리케이션 프레임웍의 과거,현재 그리고 미래 - 봄날은 간다
웹 애플리케이션 프레임웍의 과거,현재 그리고 미래 - 봄날은 간다웹 애플리케이션 프레임웍의 과거,현재 그리고 미래 - 봄날은 간다
웹 애플리케이션 프레임웍의 과거,현재 그리고 미래 - 봄날은 간다동수 장
 
2015 FOSScon NAVER OSS Governance
2015 FOSScon NAVER OSS Governance2015 FOSScon NAVER OSS Governance
2015 FOSScon NAVER OSS GovernanceNAVER Engineering
 
2016 네이버sw기술소개
2016 네이버sw기술소개2016 네이버sw기술소개
2016 네이버sw기술소개NAVER Engineering
 
취약점(Vulnerability) db 구조 설명
취약점(Vulnerability) db 구조 설명취약점(Vulnerability) db 구조 설명
취약점(Vulnerability) db 구조 설명eungjin cho
 
Web Framework (웹 프레임워크)
Web Framework (웹 프레임워크)Web Framework (웹 프레임워크)
Web Framework (웹 프레임워크)Junsu Kim
 

En vedette (9)

[C1]웹서비스, 빠를수록 좋다
[C1]웹서비스, 빠를수록 좋다[C1]웹서비스, 빠를수록 좋다
[C1]웹서비스, 빠를수록 좋다
 
Korea linuxforum2014 html5game-sangseoklim
Korea linuxforum2014 html5game-sangseoklimKorea linuxforum2014 html5game-sangseoklim
Korea linuxforum2014 html5game-sangseoklim
 
레이스 컨디션 기초(Basic Race Condition)
레이스 컨디션 기초(Basic Race Condition)레이스 컨디션 기초(Basic Race Condition)
레이스 컨디션 기초(Basic Race Condition)
 
웹 애플리케이션 프레임웍의 과거,현재 그리고 미래 - 봄날은 간다
웹 애플리케이션 프레임웍의 과거,현재 그리고 미래 - 봄날은 간다웹 애플리케이션 프레임웍의 과거,현재 그리고 미래 - 봄날은 간다
웹 애플리케이션 프레임웍의 과거,현재 그리고 미래 - 봄날은 간다
 
2015 FOSScon NAVER OSS Governance
2015 FOSScon NAVER OSS Governance2015 FOSScon NAVER OSS Governance
2015 FOSScon NAVER OSS Governance
 
2016 네이버sw기술소개
2016 네이버sw기술소개2016 네이버sw기술소개
2016 네이버sw기술소개
 
취약점(Vulnerability) db 구조 설명
취약점(Vulnerability) db 구조 설명취약점(Vulnerability) db 구조 설명
취약점(Vulnerability) db 구조 설명
 
Web Framework (웹 프레임워크)
Web Framework (웹 프레임워크)Web Framework (웹 프레임워크)
Web Framework (웹 프레임워크)
 
2017 ict 대전망 framework
2017 ict 대전망 framework2017 ict 대전망 framework
2017 ict 대전망 framework
 

Similaire à The comprehensive guide for optimizing the performance of mobile HTML5 Web applications

01.모바일 프레임워크 이론
01.모바일 프레임워크 이론01.모바일 프레임워크 이론
01.모바일 프레임워크 이론Hankyo
 
네이티브 웹앱 기술 동향 및 전망
네이티브 웹앱 기술 동향 및 전망네이티브 웹앱 기술 동향 및 전망
네이티브 웹앱 기술 동향 및 전망Wonsuk Lee
 
네이티브 웹앱 기술 동향 및 전망
네이티브 웹앱 기술 동향 및 전망네이티브 웹앱 기술 동향 및 전망
네이티브 웹앱 기술 동향 및 전망Wonsuk Lee
 
하이브리드 앱(Hybrid App)
하이브리드 앱(Hybrid App)하이브리드 앱(Hybrid App)
하이브리드 앱(Hybrid App)Changhwan Yi
 
목적에 맞게 Angular, React, Vue
목적에 맞게 Angular, React, Vue목적에 맞게 Angular, React, Vue
목적에 맞게 Angular, React, VueGunhee Lee
 
강의자료 차세대 웹(Html5) 플랫폼의 동향과 구축 방안
강의자료   차세대 웹(Html5) 플랫폼의 동향과 구축 방안강의자료   차세대 웹(Html5) 플랫폼의 동향과 구축 방안
강의자료 차세대 웹(Html5) 플랫폼의 동향과 구축 방안욱래 김
 
[124] 하이브리드 앱 개발기 김한솔
[124] 하이브리드 앱 개발기 김한솔[124] 하이브리드 앱 개발기 김한솔
[124] 하이브리드 앱 개발기 김한솔NAVER D2
 
웹 2.0 기술 소개 (2006)
웹 2.0 기술 소개 (2006)웹 2.0 기술 소개 (2006)
웹 2.0 기술 소개 (2006)Channy Yun
 
HTML5 융합 기술 표준화 동향
HTML5 융합 기술 표준화 동향HTML5 융합 기술 표준화 동향
HTML5 융합 기술 표준화 동향Jonathan Jeon
 
[141]지난 1년간의 웨일 브라우저와 그 미래 (부제: 제품 매니저가 들려주는 생생한 기술/제품 이야기)
[141]지난 1년간의 웨일 브라우저와 그 미래 (부제: 제품 매니저가 들려주는 생생한 기술/제품 이야기)[141]지난 1년간의 웨일 브라우저와 그 미래 (부제: 제품 매니저가 들려주는 생생한 기술/제품 이야기)
[141]지난 1년간의 웨일 브라우저와 그 미래 (부제: 제품 매니저가 들려주는 생생한 기술/제품 이야기)NAVER D2
 
Enterprise mobile standard, morpheus 모피어스 모바일 표준 플랫폼
Enterprise mobile standard, morpheus 모피어스 모바일 표준 플랫폼Enterprise mobile standard, morpheus 모피어스 모바일 표준 플랫폼
Enterprise mobile standard, morpheus 모피어스 모바일 표준 플랫폼MarketingUracle
 
Mozilla 오픈 웹 모바일 플랫폼 (2012)
Mozilla 오픈 웹 모바일 플랫폼 (2012)Mozilla 오픈 웹 모바일 플랫폼 (2012)
Mozilla 오픈 웹 모바일 플랫폼 (2012)Channy Yun
 
차세대 웹비즈니스를 위한 "HTML5"
차세대 웹비즈니스를 위한 "HTML5"차세대 웹비즈니스를 위한 "HTML5"
차세대 웹비즈니스를 위한 "HTML5"Changhwan Yi
 
HTML5 스펙 소개
HTML5 스펙 소개HTML5 스펙 소개
HTML5 스펙 소개Toby Yun
 
Dreamweaver CS5.5 를 이용한 jQueryMobile 개발
Dreamweaver CS5.5 를 이용한 jQueryMobile 개발Dreamweaver CS5.5 를 이용한 jQueryMobile 개발
Dreamweaver CS5.5 를 이용한 jQueryMobile 개발JongKwang Kim
 
my activities before getting a job
my activities before getting a jobmy activities before getting a job
my activities before getting a jobDeo Kim
 
K모바일발표 120113 남들보다뛰어난앱만들기_공유용
K모바일발표 120113 남들보다뛰어난앱만들기_공유용K모바일발표 120113 남들보다뛰어난앱만들기_공유용
K모바일발표 120113 남들보다뛰어난앱만들기_공유용jinwook shin
 
HTML5 기반 다매체 연동형 서비스 발전 방향(티비스톰 정운교 이사)
HTML5 기반 다매체 연동형 서비스 발전 방향(티비스톰 정운교 이사)HTML5 기반 다매체 연동형 서비스 발전 방향(티비스톰 정운교 이사)
HTML5 기반 다매체 연동형 서비스 발전 방향(티비스톰 정운교 이사)JeongHeon Lee
 

Similaire à The comprehensive guide for optimizing the performance of mobile HTML5 Web applications (20)

01.모바일 프레임워크 이론
01.모바일 프레임워크 이론01.모바일 프레임워크 이론
01.모바일 프레임워크 이론
 
네이티브 웹앱 기술 동향 및 전망
네이티브 웹앱 기술 동향 및 전망네이티브 웹앱 기술 동향 및 전망
네이티브 웹앱 기술 동향 및 전망
 
네이티브 웹앱 기술 동향 및 전망
네이티브 웹앱 기술 동향 및 전망네이티브 웹앱 기술 동향 및 전망
네이티브 웹앱 기술 동향 및 전망
 
하이브리드 앱(Hybrid App)
하이브리드 앱(Hybrid App)하이브리드 앱(Hybrid App)
하이브리드 앱(Hybrid App)
 
목적에 맞게 Angular, React, Vue
목적에 맞게 Angular, React, Vue목적에 맞게 Angular, React, Vue
목적에 맞게 Angular, React, Vue
 
모바일환경과 개발방향
모바일환경과 개발방향 모바일환경과 개발방향
모바일환경과 개발방향
 
강의자료 차세대 웹(Html5) 플랫폼의 동향과 구축 방안
강의자료   차세대 웹(Html5) 플랫폼의 동향과 구축 방안강의자료   차세대 웹(Html5) 플랫폼의 동향과 구축 방안
강의자료 차세대 웹(Html5) 플랫폼의 동향과 구축 방안
 
[124] 하이브리드 앱 개발기 김한솔
[124] 하이브리드 앱 개발기 김한솔[124] 하이브리드 앱 개발기 김한솔
[124] 하이브리드 앱 개발기 김한솔
 
웹 2.0 기술 소개 (2006)
웹 2.0 기술 소개 (2006)웹 2.0 기술 소개 (2006)
웹 2.0 기술 소개 (2006)
 
HTML5 융합 기술 표준화 동향
HTML5 융합 기술 표준화 동향HTML5 융합 기술 표준화 동향
HTML5 융합 기술 표준화 동향
 
[141]지난 1년간의 웨일 브라우저와 그 미래 (부제: 제품 매니저가 들려주는 생생한 기술/제품 이야기)
[141]지난 1년간의 웨일 브라우저와 그 미래 (부제: 제품 매니저가 들려주는 생생한 기술/제품 이야기)[141]지난 1년간의 웨일 브라우저와 그 미래 (부제: 제품 매니저가 들려주는 생생한 기술/제품 이야기)
[141]지난 1년간의 웨일 브라우저와 그 미래 (부제: 제품 매니저가 들려주는 생생한 기술/제품 이야기)
 
Enterprise mobile standard, morpheus 모피어스 모바일 표준 플랫폼
Enterprise mobile standard, morpheus 모피어스 모바일 표준 플랫폼Enterprise mobile standard, morpheus 모피어스 모바일 표준 플랫폼
Enterprise mobile standard, morpheus 모피어스 모바일 표준 플랫폼
 
Mozilla 오픈 웹 모바일 플랫폼 (2012)
Mozilla 오픈 웹 모바일 플랫폼 (2012)Mozilla 오픈 웹 모바일 플랫폼 (2012)
Mozilla 오픈 웹 모바일 플랫폼 (2012)
 
차세대 웹비즈니스를 위한 "HTML5"
차세대 웹비즈니스를 위한 "HTML5"차세대 웹비즈니스를 위한 "HTML5"
차세대 웹비즈니스를 위한 "HTML5"
 
HTML5 스펙 소개
HTML5 스펙 소개HTML5 스펙 소개
HTML5 스펙 소개
 
Dreamweaver CS5.5 를 이용한 jQueryMobile 개발
Dreamweaver CS5.5 를 이용한 jQueryMobile 개발Dreamweaver CS5.5 를 이용한 jQueryMobile 개발
Dreamweaver CS5.5 를 이용한 jQueryMobile 개발
 
my activities before getting a job
my activities before getting a jobmy activities before getting a job
my activities before getting a job
 
Webtech
WebtechWebtech
Webtech
 
K모바일발표 120113 남들보다뛰어난앱만들기_공유용
K모바일발표 120113 남들보다뛰어난앱만들기_공유용K모바일발표 120113 남들보다뛰어난앱만들기_공유용
K모바일발표 120113 남들보다뛰어난앱만들기_공유용
 
HTML5 기반 다매체 연동형 서비스 발전 방향(티비스톰 정운교 이사)
HTML5 기반 다매체 연동형 서비스 발전 방향(티비스톰 정운교 이사)HTML5 기반 다매체 연동형 서비스 발전 방향(티비스톰 정운교 이사)
HTML5 기반 다매체 연동형 서비스 발전 방향(티비스톰 정운교 이사)
 

The comprehensive guide for optimizing the performance of mobile HTML5 Web applications

  • 1. 1 Mobile Web Application 개발 방법론: 설계, 구현 및 최적화 Guide 임상석 Manager sangseok.lim@sk.com SD 개발팀, 플랫폼 기술원
  • 2. 자료 목적 2 대상: 실무 Web App 개발자 및 개발 과제 Project Lead 목적: HTML5를 포함 Web 기술을 기반으로 한 Mobile향 Web Application 개발시 필요한 SW 설계, 구현 및 최적화 방법에 대한 End-to-End 상세 기술 Guide 제공
  • 3. Contents 3 ¨  Mobile Web Application 정의 l  ¨  Server-hosted, Hybrid Mobile Web Application SW Architecture 설계 사례 l  l  Audio 기능 개발: Sound Manager2 l  Fragmentation handling: Modernizr l  ¨  UI/UX 개발: jQuery, jQuery Mobile Common utilities: touch library, URL bar control Mobile Web Application Platform Architecture l  ¨  Mobile browser engine architecture Mobile Web Application End-To-End 성능 최적화 방법론 l  Front-end단 성능 최적화 guide l  From server to client 최적화: profiling tool 및 best practice
  • 4. HTML5 Mobile Web App 전망 4 SAP's Head of Mobility, Sanjay Poonen predicted that by 2015, 50% of enterprise mobility applications would be HTML5 based. In another interview I conducted this week with Sencha's CEO, Michael Mullany, he predicted that by 2014,50% of enterprise mobility applications would be HTML5 based, 20% would be native, and 30% would be a hybrid of HTML5. from http://www.sys-con.com/node/2263927 2015년 Mobile OS Market share 예상 Android: 50.6%, iOS 20.6%, Microsoft 24.0%, Bada 1.8% Source: Gartner (April 2012)
  • 5. HTML5 Web App 기술 분야 5 SW 개발자 (Programming) HTML5/Web App 개발자 (Programming) Web designer (Publishing) ss Java/C++/Objective C Native API Algorithm Compiling HW 최적화 ARM GPU HTML5 HTML4 CSS3.0 CSS2.1 Flash JavaScript JavaScript (system/module/logic) (DHTML) DOM Browser
  • 6. Mobile Web Application 분류 6 ¨  동작 및 배포 방식에 따른 구분 l  l  ¨  Server hosted (except for App cache, Local Storage ) Hybrid (packaged and locally installed) 강좌 목표: Server Hosted의 Pure Web App 개발 기술 Practice Remote Server Web Data Web Data Web Data HTML5 App On target device Native Web App WebView (WebKit) WebView (WebKit) HTML5 Native App Part Container/Binder (PhoneGap, AppMobi) WebView Binder (WebKit) Android/iOS Android/iOS Android/iOS Browser
  • 7. App Store로부터 Runaway 7 ¨  App Store 통제 l  l  ¨  run/own/censor ed by platform/OEM/carrier Sale/in-app billing commission 시장 예: runaway from app store, into browser l  Amazon -  l  Offline access, cloud sync, Native app look&feel GUI Facebook -  -  l  App center strategy W3C community group for browser fragmentation and billing Financial Times -  Offline access, Native app look&feel GUI -  Auto download
  • 8. Native to Web 이전 검토시 고려사항 8 주요 Factor 서비스 유형 Device 호환성 고려 사항 Web App으로 개발하기에 적합한 경우 1)  News나 SNS와 같이 Info-tainment 성격의 서비스 2)  웹 브라우저로 이미 서비스가 되고 있는 경우 3)  서버 Update 및 Data sync가 빈번하게 발생하는 서비스 Multi- Platform/Device 대상인 경우 Web App이 적합함 Server-based Server-based의 경우 Web App으로 Migration 용이함 ( 단, T Store와 같이 http 방식이 아닌 TCP 소켓 통신의 경우 프로토콜의 수정 개발이 필요 ) HTML 5만으로 client 구현 가능한 경우 Data provision 방식 Client-based Native component를 사용해야만 하는 경우 1)  2)  Performance-constrain t 1)  2)  Web 기반 client를 개발해야 하는 비용 발생 간단한 App들이 이 범주에 속함 1)  2)  3)  4)  Hybrid 방식으로만 가능 NDK를 WebView에 정합하기 위한 비용 발생 NDK 사용하는 부분은 Cross-Platform하지 않음 T map이 대표적인 예임 기본적으로 Web App은 data loading, parsing, rendering 의 구조이기 때문에 Native 대비 성능이 느릴 수 밖에 없음 Hybrid 방식으로 Native component와 WebView 사이의 Data 전송이 발생하게 되면 Data 복사에 따른 추가의 overhead 발생 Ex) Device API 호출 시 overhead 발생 1)  최적화되지 않은 기능을 많이 사용하면 안됨 Ex) Vector Graphic 위해 Canvas 2D를 많이 사용하면 성능이 저하됨
  • 9. 시장 사례 분석 9 ¨  Melon 사례 l  l  ¨  Server hosted: m.melon.com, t.melon.com Hybrid: iOS 및 Android app 11번가 사례 l  Server hosted: m.11st.co.kr l  Hybrid: iOS 및 Android app
  • 10. Web App 개발 요구사항 10 ¨  본 강좌에서 가정하는 Mobile Web app의 상위 수준 요구사항으로 이 를 만족하는 audio streaming용 Web application 개발 상품화 하는 시 나리오를 설정 l  단말에서 구동되는 Mobile browser내에서 동작 해야함 l  Native 수준의 뒤 떨어지지 않는 GUI/UX 를 제공하여야 함 l  Audio playback을 제공해야함 l  Cross-platform 지원 해야함 -  Android 2.1/2.2/2.3/3.0/4.0 및 Chrome for Android -  IOS 3.0/4.0/5.0/6.0 -  Blackberry OS 6.0/7.0 l  UX 저하가 없는 수준의 성능을 제공 해야함 l  작성한 코드는 다른 Application 개발에도 재활용이 가능해야함
  • 11. Web App 개발 요구사항: 11 cross-platform
  • 12. UI 상세 명세서 일부 12 ¨  ¨  아래의 3분류의 화면 Template 제공하고 화면간 이동 및 이동시 transition effect를 지원 해야함 노래 목록은 위 아래 scroll이 가능해야하고 이때 상단 및 하단 메뉴는 화면에 고정 되어있어야 함 고정 화면 전환 및 효과 화면 전환 및 효과 고정
  • 13. Web App SW Arch. 구성 예 13 ¨  Open source기반 Web application SW 구조 l  ¨  Open source 활용시 다양한 configuration이 가능하고 하나의 예임 Open source 선택시 필수 고려사항 l  Community가 활성화정도, 안정 버전 release 주기 l  License 종류, 회사 편향도 HTML5 audio application UI Framework jQuery Mobile + plug-in jQuery + plug-in iScroll (JS Scroller) Fast Button URL Bar Handle r Audio FW Fragmentation Handling Sound Manager2 Modernizr DOM (Document Object Model) Browser WebView (WebKit) Android/iOS/Blackberry OS/Kindle Fire Application processor, GPU
  • 14. Page Speed: Mobile 11번가 14
  • 15. jQuery Mobile (JQM) 15 ¨  Smart phone과 tablet을 위한 touch 최적화된 UI widget 제공 ¨  cross-platform을 진중히 추구하는 Touch 최적화 Web Platform ¨  jQuery plugin 및 widget pattern으로 개발됨: $.mobile ¨  Theming 지원: http://jquerymobile.com/themeroller/ http://jquerymobile.com/demos/1.1.0/
  • 16. JQM Pagination 16 ¨  단일 DOM tree 내에 2개 이상의 application view를 page로 구분하여 show/hide를 포함한 관리가 가능하도록 기능 제공 ¨  개별 HTML에 저장된 page를 load하는 방식에 비해 속도, 데이터 공유를 위 해서 필수적인 기법 <body> <div data-role="page“ id=“album_main”> <div data-role="content"> </div><!-- /content --> </div><!-- /page --> <div data-role="page“ id=“page_home”> <div data-role="header"> <h1>I’am header</h1> </div><!-- /header --> <div data-role="content"> </div><!-- /content --> <div data-role="footer"> <h1> Footer </h1> </div><!-- /footer --> </div><!-- /page --> <div data-role="page“ id=“page_playlist”> <div data-role="header"> <h1>I’am header</h1> </div><!-- /header --> <div data-role="content"> </div><!-- /content --> <div data-role="footer"> <h1> Footer </h1> </div><!-- /footer --> </div><!-- /page --> </body> page show 및 page간 전환시 network loading 지연 미 발생
  • 17. JQM Widget 17 ¨  지원하는 widgets l  Pages, dialogs, toolbars, listview, button, form element, accordion, collapsibles
  • 18. Listview 예제 18 <!DOCTYPE html> <html> <head> <title>My Page</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="http://code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.min.css" /> <script src="http://code.jquery.com/jquery-1.7.1.min.js"></script> <script src="http://code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.min.js"></script> </head> <body> <div data-role="page"> <div data-role="header"> <h1>I’am header</h1> </div><!-- /header --> <div data-role="content"> <ul data-role="listview" data-inset="true" data-filter="true"> <li><a href="#">Acura</a></li> <li><a href="#">Audi</a></li> <li><a href="#">BMW</a></li> <li><a href="#">Cadillac</a></li> <li><a href="#">Ferrari</a></li> </ul> </div><!-- /content --> <div data-role="footer"> <h1> Footer </h1> </div><!-- /footer --> </div><!-- /page --> </body> </html>
  • 19. Navbar 추가 19 <div data-role="header" data-position="fixed"> <div data-role="footer" data-position="fixed"> <div data-role="navbar"> <ul> <div data-role="navbar"> <li><a href="#">One</a></li> <ul> <li><a href="#">Two</a></li> <li><a href="#">One</a></li> <li><a href="#">Three</a></li> <li><a href="#">Two</a></li> </ul> <li><a href="#">Three</a></li> </div><!-- /navbar --> </ul> </div><!-- /footer --> </div><!-- /navbar --> </div><!-- /header --> 상단 고정 하단 고정
  • 20. Multi page template 20 <body> <!-- Start of first page --> <div data-role="page" id="foo"> Page foo <div data-role="header> <h1>Foo</h1> </div><!-- /header --> <div data-role="content"> <p>I'm first in the source order so I'm shown as the page.</p> <p>View internal page called <a </div><!-- /content --> href="#bar" data-transition="pop">bar</a></p> <div data-role="footer"> <h4>Page Footer</h4> </div><!-- /footer --> </div><!-- /page --> <!-- Start of second page --> <div data-role="page" id="bar"> pop slide Page bar <div data-role="header"> <h1>Bar</h1> </div><!-- /header --> <div data-role="content"> <p>I'm the second in the source order so I'm hidden when the page loads. I'm just shown if a link that references my ID is beeing clicked.</p> <p><a href="#foo" </div><!-- /content --> <div data-role="footer"> <h4>Page Footer</h4> </div><!-- /footer --> </div><!-- /page --> </body> data-transition="slide">Back to foo</a></p>
  • 21. External page handling (1/2) 21 ¨  현재 html이 아닌 별도의 html에 있는 page를 AJAX load후 DOM에 inject하는 기능 l  <head> 내부 부분 parsing 하지 않음 -  l  JS 파일, <script> block, CSS를 load 하지 않음 Page-specific JavaScript 및 CSS는 직접 loading 해야함 -  -  Page div 내에 포함 <body> tag내에 포함 후 pageInit에서 초기화 <div data-role="content"> <a href="external.html" </div><!-- /content --> data-transition="pop">bar</a> main.html <!DOCTYPE html> <html> <head> <title>My Page</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="http://jquery.mobile-1.1.0.min.css" /> <script src="http://code.jquery.com/jquery-1.7.1.min.js"></script> <script src="http://jquery.mobile-1.1.0.min.js"></script> </head> <body> <div data-role="page"> <div data-role="header"> <h1>I’am header</h1> </div><!-- /header --> <div data-role="content"> </div><!-- /content --> </div><!-- /page --> </body> </html> external.html
  • 22. External page handling (2/2) 22 ¨  Page prefetching l  external page를 전환 속도 개선을 위해 prefetch <a href="prefetchThisPage.html" data-prefetch> ... </a> programmatically load 방식 $.mobile.loadPage( pageUrl, { showLoadMsg: false } ); ¨  DOM size 자동 관리 l  l  ¨  숨겨진 page (pagehide event)의 DOM을 detach 후 제거 à memory 사용량 개선 기능 show시 자동으로 AJAX를 통해 다시 load함 Page를 DOM에 caching 하는 기능 l  hide시 DOM에서 detach후 해당 page를 별도로 cache <div data-role="page" id="cacheMe" data-dom-cache="true">
  • 23. Web based WISWYG Editor 23 ¨  l  ¨  Codiqa GUI editor ThemeRoller Mobile l  Theme editor ThemeRoller Mobile Codiqa (charged)
  • 24. UI 명세서 중간 점검 24 ¨  JQM widget set 구성으로 구현 가능 l  Page 3개, Listview, header/footer with position fixed 고정 화면 전환 및 효과 화면 전환 및 효과 고정
  • 25. HTML5 Data- attribute 25 ¨  data-* attribute 추가 l  Custom attribute 정의하여 사용 가능 <li id="appDeveloperInfo"class="user" data-name="sangseok" data-company="SK planet" data-lang="korea" data-food="Noodle"> <span>고맙습니다</span> </li> ¨  저장값 접근 방식 l  JavaScript/DOM API 활용 var appDeveloperInfo = document.getElementById(‘appDeveloperInfo’); var appDeveloperName = appDeveloperInfo.getAttribute(‘data-name’); l  Jquery jQuery.find(‘[data-name="sangseok"]’); l  Jquery Mobile $("li:jqmData(role=’name’")
  • 26. JQM Data- attribute 26 ¨  JQM은 HTML 5 Data- attribute를 Widget 마다 정의하여 사용 l  l  ¨  data-role, data-inset, data-position, data-corner, data-dom-cache http://jquerymobile.com/demos/1.1.0/docs/api/data-attributes.html JQM의 data enhance l  초기화시 해당 data- attribute에 따라 element를 선택후 해 당 element를 enhance를 수행함 -  -  새로운 CSS class 적용 -  ¨  Extra markup 추가 Event handler 등록 JQM 1.1.0에서는 data- attribute를 통한 enhance를 막는 기법 을 제공 l  data-enhance=``false’’
  • 27. JQM Event (1/2) 27 ¨  Touch event l  ¨  tap, taphold, swipe, swipeleft,swiperight Virtual mouse events l  l  ¨  vmouseover, vmousedown, vmousemove, vmouseup vclick, vmousecancel Orientation change l  ¨  orientationchange Scroll events l  scrollstart, scrollstop
  • 28. JQM Event (2/2) 28 ¨  Page load events l  ¨  Page change events l  ¨  pagebeforeshow, pagebeforehide, pageshow, pagehide Page initialization evets l  ¨  pagebeforechange, pagechange, pagechangefailed Page transition events l  ¨  pagebeforeload, pageload, pageloadfailed pagebeforecreate, pagecreate, pageinit Layout events l  updatelayout
  • 29. JQM Event Binding 29 ¨  jQuery의 live() 또는 bind() 를 사용 l  l  l  live(): jQuery selector에 현재 또는 미래에 match되는 모든 element에 event handler를 attach bind():jQuery selector에 현재 match되는 모든 element에 event handler를 attach Delegate(): Document (default, 변경가능) Node에서 bubbling되 는 event에 대한 event handler를 attach $( document ).bind( "pagebeforeload", function( event, data ){ // Let the framework know we're going to handle the load. event.preventDefault(); // ... load the document then insert it into the DOM ... // at some point, either in this callback, or through // some other async means, call resolve, passing in // the following args, plus a jQuery collection object // containing the DOM element for the page. data.deferred.resolve( data.absUrl, data.options, page ); }); $( 'div' ).live( 'pageshow',function(event, ui){ alert( 'This page was just hidden: '+ ui.prevPage); });
  • 30. JQM Method 30 ¨  Jquery.mobile object를 통해 각종 method를 제공함 l  $.mobile.changePage l  $.mobile.loadPage: external page load l  $.mobile.fixedToolbars.hide l  $.mobile.silentScroll -  l  ¨  주어진 Y위치로 onscroll trigger하지 않고 scroll $.mobile.activePage Full list는 아래에서 확인 가능 l  http://jquerymobile.com/demos/1.1.0/docs/api/methods.html //transition to the "confirm" page with a "pop" transition without tracking it in history $.mobile.changePage( "../alerts/confirm.html", { transition: "pop", reverse: false, changeHash: false });
  • 31. JQM VS Sencha Touch (1/2) 31 jQuery Mobile Sencha Touch 개발사 jQuery 진영에서 개발 ExtJS 개발사에서 개발 개발자 Pool 125 contributor, 9 company supporter※ 11 Sencha Employer 개발 Script jQuery 기반 ExtJS 기반 개발 방식 마크업 기반 (Web Designer 친화적) 스크립트 기반 (JS Programmer 친화적) 테마 특징 CSS3 활용, 테마롤러 도구 지원 Sass 기반 핵심 라이브러리 jquery-mobile-1.0.js(210KB) jquery.mobile-1.0css(81KB) jquery.mobile-1.0.min.js(80KB) – 경량화 버전 jquery.mobile-1.0.min.css(48KB) – 경량화 버전 (1.1.1 기준) sencha-touch.js (367KB) sencha-touch.css (144KB) sencha-touch-debug.js(746KB) –개발 버전 (2.0.0 기준) sencha-touch.js (92KB) sencha-touch.css (143KB) sencha-touch-debug.js(423KB) –개발 버전 지원 모바일 플랫폼 iOS 3.2-5.0, Android 2.1-2.3/3.0, Window Phone 7-7.5, Black Berry 6.0+ , Palm WebOS (1.4-2.0)/3.0, iOS3.0 +, Android 2.1+ ,Black Berry 6.0 + 공식 Homepage http://jquerymobile.com http://sencha.com/products/touch 개발 버전 1.1.0 2.0 개발 난이도 중 상 특이사항 개방성: 순수 Open Source 과제로 운영 Product 개발 지원을 위한 외부 전문 Consulting 업체 운영중 Sench Touch Charts 유료버전 제공 AT&T의 Browser 기반 HTML5 AppStore 라이선스 MIT (jQuery 프로젝트와 동일) GPL (jQuery 프로젝트와 동일) Commercial S/W License (현재 무료) Commercial OEM License(유료) Open Source License (GPL v3) *Saas: Ruby기반의 CSS 생생 library ※Mozilla, Palm, BlackBerry, Adobe, Jive, DotMobi, Nokia, DeviceAtalas, filament
  • 32. JQM VS Sench Touch (2/2) 32 jQuery Mobile <head> js파일 include Sencha Touch <head> </head> <body> <div data-role="page" id="sub" data-add-backbtn="true" data-fullscreen="true"> <div data-role="header" data-position="fixed" > <h1>sub page</h1> </div> <div data-role="content"> <ul data-role="listview"> <li><a href="#">Acura</a></li> <li><a href="#">Audi</a></li> <li><a href="#">BMW</a></li> <li><a href="#">Honda</a></li> <li><a href="#">Hyundai</a></li> </ul> </div><!-- /content --> </body> Ext.regModel('Contact', { fields: ['Name'] }); demos.ListStore = new Ext.data.Store({ model: 'Contact', data: [ {Name: 'Acura'}, {Name: 'Audi'}, {Name: 'BMW'}, {Name: 'Honda'}, {Name: 'Hyundai'} ] }); demos.List = new Ext.TabPanel ({ items: [{ title: 'Simple', layout: Ext.is.Phone ? 'fit' : { type: 'vbox', align: 'center', pack: 'center' } }] });
  • 33. UI 명세서 중간 점검 33 ¨  Native 수준에 뒤 떨어지지 않는 GUI/UX 제공해야함 ¨  Cross-platform 지원 해야함 -  -  ¨  Android 2.1/2.2/2.3/3.0/4.0 및 Chrome for Android IOS 3.0/4.0/5.0 CSS position:fixed property 지원 여부 -  WebKit version 533미만 미지원 고정 화면 전환 및 효과 고정 position:fixed: window를 기준으로 위치를 고정
  • 34. CSS position:fixed issue 34 ¨  CSS position:fixed 정의 l  l  ¨  element의 위치를 containing block이 아닌 window를 기준점으로 위치 를 정함 Web page 를 scroll하여도 위치가 고정되어 각종 메뉴구성에 쓰임 CSS position fixed 구현 방식 l  Android 2.3 이상, iOS 5.0이상 정상 동작 l  Android 2.2 이하 오동작 -  l  window기준으로 첫번째 rendering위치에 고정 IOS 4.0이하 -  l  고정 Web page의 끝 (마지막 element 다음)에 붙임 Android 2.3 삼성 단말 오동작 고정
  • 35. CSS position:fixed 처리 35 ¨  JQM에서 position:fixed 처리 방식 l  Browser 엔진에서 지원시 사용 l  Browser 엔진에서 미지원시 처리 방식 -  Scroll 시작시 사라지게하고 종료시 다시 그려줌 -  Page 최상단과 하단에 position:static으로 붙임 l  ¨  중간 위치로 scroll 되어있을시 화면에 보이지 않게됨 문제점 ¤  첫번째 방식 -  -  ¤  scroll시 JavaScript 수행을 중지시키는 경우 화면 update 문제 발생 (삼성 Android 2.3 단말 포함) 지속적으로 깜빡 거려서 UX 저하 두번째 방식 -  UX 관점에서 application이라기 보다는 web page의 느낌임
  • 36. Fixed toolbar 지원 대안 1 36 ¨  overflow:scroll을 이용한 우회법 l  l  ¨  Fixed toolbar의 position은 fixed가 아닌 absolute, static, inline을 사용하 여 scroll하는 영역 위 아래에 고정 overflow:scroll을 이용하여 content 영역만을 scroll 문제점 l  overflow:scroll Android 2.3이하에서 미지원 l  IOS 4.0이상 지원하나 두손가락 gesture를 사용: UX 일관성 깨짐 l  지원이되더라도 화면 갱신 속도가 매우느림 position:fixed viewport position:inline content viewport position:fixed position:inline IOS 5.0 부터는 -webkit-overflow-scrolling:touch 지원 content overflow:scroll
  • 37. JavaScript Scroller: iScroll 37 ¨  iScroll JavaScript scroller: cubiq.org/iscroll-4 l  overflow:auto, touch event, -webkit-transform을 활용한 개선 l  -webkit-transfrom 미지원 단말 “top” property를 JS 변경 <div data-role="page"> <div data-role="header"> <h1>I’am header</h1> </div><!-- /header --> <div data-role="content"> <div class="wrapper"> <div class="scroller"> <ul data-role="listview"> <li><a href="#">Acura</a></li> <li><a href="#">Audi</a></li> viewport <li><a href="#">BMW</a></li> <li><a href="#">Cadillac</a></li> <li><a href="#">Ferrari</a></li> </ul> </div> </div> </div><!-- /content --> <div data-role="footer"> <h1> Footer </h1> </div><!-- /footer --> </div><!-- /page --> position:absolute position:absolute <div class = scroller> -webkittransform:translate3d(0,dy,z) z-index:1 <div class = wrapper> overflow:hidden position:absolute z-index:1 touchmove event를 wrapper에 binding
  • 38. iScroll 기능 38 ¨  iScroll의 기능 l  Pull to refresh l  Pinch zoom l  Scrollbar customize l  Transition mode -  l  ¨  webkit-transform-timing-function: cubic-bezier 사용 Touch 미지원시 mouse fallback Public method l  refresh() l  scrollTo(x, y, time, relative) l  destroy
  • 39. JQM내에서 iScroll활용 39 ¨  JQM에서 page는 visible하기 전까지 그것의 height값이 계산되어지지 않음 l  refresh 시점은 해당 page가 load되고 layout이 완료된후 ¨  기타 JQM specific한 동작 styling handling이 필요함 ¨  JQM widget plugin 활용 가능 l  ¨  https://github.com/watusi/jquery-mobile-iscrollview 제약 사항 l  webkit-transform을 사용하더라도 속도가 느려지는 경우 있음 l  scroller의 style은 CPU사용량이 최소한이 되도록 최적화 해야함
  • 40. JQM 사용 Disclaimer 40 ¨  Android 3.0 이하 및 iOS 4.0이하에 적용시에는 단말별 동작 검 증 필수 l  성능 문제 -  Style 값에 따른 CPU 과다 사용 -  <a> link 포함시 단말별도 반응속도 저하 l  Fixed element 동작 문제 l  Transition 지원 문제 -  -  1.1.0부터는 target에 따라 문제가 있으면 fade로 fallback 그러나 문제가 없다고 detect되는 단말에서 실제 구현상의 이 슈, 또는 제조사 변경에 따라서 오동작 하는 경우가 다수임
  • 41. Audio 기능 제공 41 ¨  Audio관련 상세 requirement l  l  LCD off시 연속 재생 지원 l  Background mode 진입시 재생 지원 l  ¨  cross-platform으로 audio playback 지원 Playlist 지원 <audio> tag 지원 l  Android 2.1 및 2.2 미지원
  • 42. <audio> tag (1/2) 42 ¨  IOS 4.0 > l  Only user action (e.g. onclick, touchevent) action can play sound: audioElm.play() <body onLoad="document.myMovie.play()"> will not work <input type="button" value="Play" onClick="document.myMovie.play()> will work l  ¨  autoplay is disabled by Apple on purpose Browser in background mode (OEM customization) l  JavaScript timer paused l  Network paused l  Script execution paused l  setInterval suspended
  • 43. <audio> tag (2/2) 43 ¨  Audio tag event sequence on real devices l  Expected occurrence order -  l  emptied → loadstart → durationchange → loadedmetadata → loadeddata → canplay → play → playing → canplaythrough → pause → ended Measured occurrence order -  IOS 5.1 emptied → loadstart → suspend → durationchange → loadedmetadata → canplay → stalled → play → playing → progress → canplaythrough → progress → stalled → pause → ended -  Android 2.3 (Galaxy Note) emptied → loadstart → durationchange → progress → durationchange → loadedmetadata → loadeddata → canplay → canplaythrough → play → playing → ended
  • 44. Sound Manager 2 44 ¨  <audio> tag 와 Flash를 이용한 cross-platform audio playback 지원 l  ¨  App developer에게는 단일 API를 제공 Sound Manager 2 API (program template) <!-- include SM2 library --> <script type="text/javascript" src="/path/to/soundmanager2.js"></script> <script type="text/javascript"> soundManager.url = '/path/to/sm2-flash-files/'; // directory where SM2 .SWFs live . // soundManager.debugMode = false; // The basics: onready() callback soundManager.onready(function(){ // SM2 has loaded – no`w you can create and play sounds! var mySound = soundManager.createSound({ id: 'aSound', url: '/path/to/an.mp3' // onload: myOnloadHandler, // other options here.. }); mySound.play(); Not }); </script> verified for Mobile OS YET!!
  • 45. Playlist 연속 재생 45 ¨  LCD off 및 background 모드에서 연속재생 (Browser) l  <audio> tag의 구현 및 browser의 동작 방식에 따라 연속 재생 기 술적으로 불가 -  -  l  iOS Safari (possible, but not robust) Android browser (almost impossible) 기술 이슈 예 -  -  ¨  LCD off mode시 JavaScript timer fire를 suspend 이미 DOM loading된 음악 재생은 가능하나, network를 통해 신규로 음악 loading 불가 현 시점에서 가장 안전한 방법 l  Hybrid application으로 변경 -  Hybrid application내의 WebView에서 HTML app loading시 LCD off 모드에서 연속 재생 가능
  • 46. Native-like GUI: Full screen 46 ¨  iOS의 Web App mode로 full screen 만들기 l  Full screen 만들기 -  l  Status bar 설정 -  l  <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent"> 시작 화면 -  ¨  <meta name=”apple-mobile-web-app-capable” content=”yes> <link rel="apple-touch-startup-image" href="loading.png" /> Android에서 Web app mode l  Full screen mode 미지원 l  Bookmark 등록 지원 http://developer.apple.com/library/safari/#documentation/appleapplications/reference/SafariHTMLRef/Articles/MetaTags.html
  • 47. Native-like GUI: Full screen 47 ¨  URL bar hiding되는 browser에서 URL bar를 hiding시키는 조건 을 만족시키는 logic 구현 l  l  ¨  Android 및 Web app mode가 아닌 iOS Safari browser 적용 Web page의 height를 URL bar height와 window.innerHeight를 더한 값 으로 set Disclaimer l  l  l  Device 별 URL bar 크기 차이 URL bar hiding animation 도중 window는 계속적으로 resize 됨 var setupScroll = window.onload = function() { if (ios) { var height = document.documentElement.clientHeight; if (iphone && !fullscreen) height += 60; page.style.height = height + 'px'; } else if (android) page.style.height = (window.innerHeight + 56) + 'px' } setTimeout(scrollTo, 0, 0, 1); }; URL bar hiding animation도중 멈추는 현상 발생 (삼성 Galaxy Note/HD) https://gist.github.com/1172490
  • 48. Fast button 제작 48 ¨  ¨  browser의 onclick event는 double tap/panning 등의 처리로 지 연 (e.g. 300msec iOS)를 포함하고 이는 game에서와 같이 빠른 response를 필요로 하는 web app 개발시 제약임 onTouchStart는 지연없이 동작 ¤  ¤  <div ontouchStart=“doSomething()”> 구성 가능하나 누르는 순간 발생 onTouchEnd에서 발생시켜서 onclick을 emulation http://cubiq.org/remove-onclick-delay-on-webkit-for-iphone http://code.google.com/intl/ko-KR/mobile/articles/fast_buttons.html
  • 49. Fast Button 예제: Matteo 49 function NoClickDelay(el) { this.element = typeof el == 'object' ? el : document.getElementById(el); if( window.Touch ) this.element.addEventListener('touchstart', this, false); } NoClickDelay.prototype = { handleEvent: function(e) { switch(e.type) { case 'touchstart': this.onTouchStart(e); break; case 'touchmove': this.onTouchMove(e); break; case 'touchend': this.onTouchEnd(e); break; } }, onTouchStart: function(e) { e.preventDefault(); this.moved = false; this.theTarget = document.elementFromPoint(e.targetTouches[0].clientX, e.targetTouches[0].clientY); if(this.theTarget.nodeType == 3) this.theTarget = theTarget.parentNode; this.theTarget.className+= ' pressed'; this.element.addEventListener('touchmove', this, false); this.element.addEventListener('touchend', this, false); }, onTouchMove: function(e) { this.moved = true; this.theTarget.className = this.theTarget.className.replace(/ ?pressed/gi, ''); }, onTouchEnd: function(e) { this.element.removeEventListener('touchmove', this, false); this.element.removeEventListener('touchend', this, false); if( !this.moved && this.theTarget ) { this.theTarget.className = this.theTarget.className.replace(/ ?pressed/gi, ''); var theEvent = document.createEvent('MouseEvents'); theEvent.initEvent('click', true, true); this.theTarget.dispatchEvent(theEvent); } this.theTarget = undefined; } };
  • 50. Fast Button: Google Clickbuster 50 google.ui.FastButton = function(element, handler) { this.element = element; this.handler = handler; element.addEventListener('touchstart', this, false); element.addEventListener('click', this, false); }; google.ui.FastButton.prototype.handleEvent = function(event) { switch (event.type) { case 'touchstart': this.onTouchStart(event); break; case 'touchmove': this.onTouchMove(event); break; case 'touchend': this.onClick(event); break; case 'click': this.onClick(event); break; } }; google.ui.FastButton.prototype.onTouchStart = function(event) { event.stopPropagation(); this.element.addEventListener('touchend', this, false); document.body.addEventListener('touchmove', this, false); this.startX = event.touches[0].clientX; this.startY = event.touches[0].clientY; }; google.ui.FastButton.prototype.onTouchMove = function(event) { if (Math.abs(event.touches[0].clientX - this.startX) > 10 || Math.abs(event.touches[0].clientY - this.startY) > 10) { this.reset(); } }; google.ui.FastButton.prototype.onClick = function(event) { event.stopPropagation(); this.reset(); this.handler(event); if (event.type == 'touchend') { google.clickbuster.preventGhostClick(this.startX, this.startY); } }; google.ui.FastButton.prototype.reset = function() { this.element.removeEventListener('touchend', this, false); document.body.removeEventListener('touchmove', this, false); }; google.clickbuster.preventGhostClick = function(x, y) { google.clickbuster.coordinates.push(x, y); window.setTimeout(google.clickbuster.pop, 2500); }; google.clickbuster.pop = function() { google.clickbuster.coordinates.splice(0, 2); }; google.clickbuster.onClick = function(event) { for (var i = 0; i < google.clickbuster.coordinates.length; i += 2) { var x = google.clickbuster.coordinates[i]; var y = google.clickbuster.coordinates[i + 1]; if (Math.abs(event.clientX - x) < 25 && Math.abs(event.clientY - y) < 25) { event.stopPropagation(); event.preventDefault(); } } }; document.addEventListener('click', google.clickbuster.onClick, true); google.clickbuster.coordinates = [];
  • 51. Fragmentation handling (1/2) 51 ¨  Modernizr l  Device 상에서 Run time에 feature detection l  Feature detection scope -  CSS features: @font-face, border-image 등 -  HTML5 features: application cache, canvas 등 -  Plug- in을 추가하여 기능 확장 l  https://github.com/Modernizr/Modernizr/tree/master/feature-detects
  • 52. Fragmentation handling (2/2) 52 ¨  사용 방법 l  초기화 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>My Beautiful Sample Page</title> <script src="modernizr-1.5.min.js"></script> </head> 초기화 결과 저장 <html class="js canvas canvastext no-geolocation rgba hsla multiplebgs borderimage borderradius boxshadow opacity cssanimations csscolumns cssgradients cssreflections csstransforms csstransforms3d csstransitions video audio localstorage sessionstorage webworkers applicationcache fontface"> l  Modernizr.load Modernizr.load({ test: Modernizr.geolocation, yep : 'geo.js', nope: 'geo-polyfill.js' });
  • 53. Web App Platform Architecture 53 ¨  WebKit engine 구조 및 동작 ¨  Webkit rendering basics
  • 54. WebKit Open Source Project 54 ¨  Apple, Google 주도의 Open Source Project ¤  Committer/reviewer 분포 ¤  Committer 자격 n  n  ¤  Web 분야 투자/Leadership 간접 지표 10-20 good patch Committer Apple 39 6 Google n  Reviewer 24 32 총합 3명의 reviewer로부터 추천 Reviewer 자격 n  최소 80 good patch n  ¨  2 삼성전자 4명의 reviewer로부터 추천 (최소 한명은 다른 회사) 약 3백만 line으로 분야별로 전문 reviewer 활동 83 60 국내 committer: 4명 삼성전자: 2명 (EFL) Company100: 1명 (Brew) Intel: 1명(Gtk)
  • 55. WebKit 구조 55 ¨  WebKit은 Browser아닌 Web표준 처리를 위한 LIBRARY 집합 ¤  ¨  Mozilla Firefox, Google Chrome는 Browser가 Open Source UI, Graphics, network등은 platform 별 별도 구현 ¤  대부분의 성능의 격차는 port 구현에서 발생함 ¤  HW 가속, Image Caching, API등은 port 별 구현 ¤  Mac port는 미공개 Webkit open source 범위 Browser GUI DB Network WebView (Widget, API) HTML, CSS, JavaScript Mac Native Widget Cairo/Skia (2D graphics) Gtk OpenGL ES (3D graphics) WebKit Graphics back-end 구조 Qt Android JavaScriptCore (SFX, V8) WebCore WebKit Native Windowing Efl Plug -in Platform Port (HW 가속 포함) Mac Efl Gtk Qt Android Native Platform Webkit 기반 Browser 메모리 관리
  • 56. Chromium Browser 56 WebViewClient Browser Process TabContents URL Bar JS FrontEnd RenderViewHost Gtk Widget RenderProcessHost V8 Resource DispatcherHost Web Page Gtk Widget JIT IPC Channel WebCoreSupport RenderProcess WebCore Graphic s Layer Tree Render Tree Styl e Rule s DO M Tree Parser Loader Glib main loop (Event Queue) GPU Process Plugin Process File/DB NPAPI:: PluginHost RenderView HTTP stack IPC Channel IPC Channel UI FW Skia (2D graphics) Platform Port Resource Dispatcher ResourceLoaderBridge Gtk X server compositor OpenGL ES / EGL GPU Memory GPU Process URL bar Webview Window Buffer Indicator Frame Buffer
  • 57. Android Browser Multi-threaded 57 Browser Process WebViewClient Main Thread Tool Bar JS FrontEnd Webview Canvas Partially Cached DOM Node V8 JIT WebViewCoreThread WebCoreSupport WebCore Graphic s Layer Tree Render Tree Styl e Rule s DO M Tree Parser Loader Canvas PictureSet RenderView Message Handler (Event Queue) UI FW Platform Port Message Handler Skia (2D graphics) Gtk Surface Manager compositor OpenGL ES / EGL GPU Memory Window Buffer Indicator Frame Buffer
  • 58. Tizen Browser Multi-threaded 58 WebKit WebKit API URL Bar Evas Object JS FrontEnd WebCore Animation Controller WebCoreSupport Page Loader DOM Data JavaScriptCore (SFX) Interpreter or JIT BackingStore Evas Object Platform Port Graphics Layer Tree Render Tree Graphics Layer JS Engine Binder Render Layer Style Rule s Render Object DOM Tree Parser CSS Parser Node HTML Parser Graphics Port Layer Renderer GraphicsContext3D Resource Load Scheduler Sub Resource Loader Main Resource Loader Network Port GraphicsContext Ecore Main Loop (Event Queue) Pixman (NEON) UI FW Cairo (2D graphics) Evas X server Ecore compositor HTTP stack (libsoup) OpenGL ES / EGL GPU Memory Evas canvas URL bar Webview Window Buffer Indicator Frame Buffer
  • 59. DOM과 Render Tree 개괄 59 DOM Tree HTMLDocument 2. addChild() 1. Element 생성 Render Tree RenderView HTMLHtmlElement 6. addChild() 3. rendererIsNeeded? YES RenderBlock 5. setRender() 4. RenderBlock 생성 HTMLHeadElement rendererIsNeeded? NO HTMLTitleElement http://image.google.com HTMLStyleElement <html> <head> <title>Google</title> <style>…</style> <script>…</script> </head> <body> <div> <nobr> <span> <a href=“http://news.google.com”>News</a> </span> <span>…</span> </nobr> </div> </body> </html> HTMLScriptElement RenderBlock HTMLBodyElement HTMLDivElement RenderBlock HTMLElement(nobr) RenderInline HTMLElement(span) HTMLAnchorElement Text HTMLElement(span) RenderInline RenderInline RenderText RenderInline
  • 60. WebKit Rendering Basics(1/4) 60 ¨  내부 Data Structure <html> <head> </head> <body> <p> hello</p> <div class=“page” > <p>world</p> <div> parsing </body> </html> .page { position: absolute; width: 100%; height: 100%; -webkit-transform: translate3d(0, 0, 0); } Document RenderVie w <html> <head> RenderRoot Layer 조건별 Layer 생성 DOM node attach <body> <p> hello <p> RenderLayer1 <div> RenderText:”H ello” RenderText: ”World” world HTML/CSS file DOM Tree Render Tree RenderLayer Tree
  • 61. WebKit Rendering Basics(2/4) 61 ¨  내부 Data Structure RenderLayer 생성 조건 1) root object for the page 2) explicit CSS position properties (relative, absolute or a transform) 3) transparent 4) overflow, an alpha mask, reflection 5) <canvas> element with a 3D (WebGL) context 6) <video> element RenderVie w RenderRoot Layer Hello World RenderBoxModelObject:: requiresLayer() Z ordering RenderLayer RenderText: ”Hello” GraphicLayer RenderText: ”World” Render Tree RenderLayer Tree GraphicsLayer Tree (Texture on GPU)
  • 62. WebKit Rendering Basics(3/4) 62 ¨  Painting 절차: SW path ¤  하나의 graphic buffer를 할당 ¤  Z order에 따라 뒤에서 앞으로 칠함 Hello n  n  ¨  Hello를 주어진 buffer에 paint World를 Hello를 paint한 buffer에 칠함 World GraphicsContext: Graphic Buffer Painting 절차: HW accelerated path: Accelerated Compositing by GPU ¤  CPU graphics buffer와 GraphicsLayer 별 GPU buffer 생성 ¤  Layer 별로 painting ¤  모든 결과를 sync하여 compositing Hello Hello World GraphicsContext: Graphic Buffer on CPU GraphicsContext: Graphic Buffer on GPU World Compositing by GPU (Open GL ES)
  • 63. WebKit Rendering Basics(4/4) 63 ¨  HW accelerated path: Accelerated Compositing by GPU ¤  CSS 2D/3D transformation시 “World”를 animation 각도에 따라 매번 다시 paint 하지 않고 만들어진 texture를 GPU로 회전 후 기타 Layer와 compositing 수행 Hello GraphicsContext: Graphic Buffer on CPU ¨  Hello GraphicsContext: Graphic Buffer on GPU Compositing by GPU (Open GL ES) 장점 ¤  ¤  ¨  속도가 CPU 대비 “order of magnitude”로 빠름 3D transformation은 Accelerated Composting이 enable되어 있을때만 사용 가능 단점 ¤  ¨  메모리 사용량 증가: GPU memory를 별도로 할당 iOS 및 Android 4.0이상에서 지원
  • 64. Silky Smooth Scroll 기술(1/3) 64 ¨  “60 frame/sec” rule: 인간의 눈 고려시 최적 값 ¤  ¨  최소 16 msec 마다 한번씩 화면 갱신 필요 Reflow 연산: 50 msec~(600MHz@ARM Coretex-A8) ¤  주어진 DOM Tree에서 invalidate된 화면을 다시 re-paint Finger touch viewport
  • 65. Silky Smooth Scroll 기술(2/3) 65 ¨  BackingStore ¤  ¤  한번의 scroll로 이동 가능한 영역에 대해서 pre-rendering된 결과를 image로 caching 사용자 Scroll시 pre-rendering된 image의 일부를 cut-n-paste를 하여 viewport로 복사 Reflow/Repaint 제거 Single Image Buffer
  • 66. Silky Smooth Scroll 기술(3/3) 66 ¨  BackingStore ¤  ¤  한번의 scroll로 이동 가능한 영역에 대해서 pre-rendering된 결과를 image로 caching 사용자 Scroll시 pre-rendering된 image의 일부를 cut-n-paste를 하여 viewport로 복사 Reflow/Repaint 제거 RenderVie w RenderRoot Layer Z ordering RenderLayer RenderText: ”Hello” RenderText: ”World” GraphicLayer Viewport보다 큰 영역을 미리 rendering해서 image cache를 해둠 사용자 panning시 이미 rendering된 이미지를 복사해주기만 함
  • 67. Mobile Web App 성능 Factor 67 ¨  Battery Life ¨  CPU utilization ¨  ¨  ¨  No JS animation, use CSS animation Repaint/layout를 최소화 Memory bus utilization ¨  ¨  image file의 크기 최소화 ¨  ¨  Cache miss시 external DRAM read/write발생 JavaScript실행시 heap memory 사용량을 inspector로 측정 external device: WiFi, Modem, GPS, Decoder ¨  ¨  ¨  압축을 통해 정보량을 최소화 필요시에만 정보를 주고 받기 Latency (RTT) ¨  DNS look ups, HTTP request 송수신 GPU benefits and pitfalls ¨  ¨  Composited elements는 4배까지의 메모리 사용량 증가 가능 Battery 소진 주요 요소 CPU: P = CV2f LCD: dimm level (color AMOLED) WiFi/3G/LTE: Data 송수신 SDRAM: Data 읽기/쓰기 Flash: Data 읽기/쓰기
  • 68. End-to-End 성능 최적화 (1/2) 68 l  성능 최적화 guide 및 tip l  (성능 === Money) // true Delay 0-100ms instant 100-300ms Feels sluggish 300-1,000ms Machine is working... 1s+ Mental context switch 10s+ I’ll come back later Usability Engineering – Jakob Nielsen, 1993
  • 69. End-to-End 성능 최적화 (2/2) 69 From W3C Navigation Timing specification
  • 70. Front-end (FE) 최적화 Guide 70 ¨  ¨  Part 1: Graphics/Animation Part 2: Parsing/Layout/Rendering ¨  Part 3: JavaScript Part 4: DOM Event ¨  Part 4: Networking/Loading ¨  Part 5: jQuery ¨ 
  • 71. FE 성능 개선 Guide – Part 1 71 ¨  Graphics/Animation
  • 72. 2D/3D Animation 72 ¨  ¨  [RULE] CSS 2D/3D transforms를 이용한 2D/3D animation 구현 은 HW 가속 Accelerated Compositing 기능이 제공 되는 Mobile O S 에서만 사용한다 Mobile OS에서 HW 가속 Accelerated Compositing 지원 현황 iOS 3.0 지원 여부 ¨  iOS 4.0 iOS 5.0 Android 2.1 Android 2.2 Android 2.3 Android 3.0 Android 4.0 X O O X§ X§ X§ X O JavaScript를 통한 지원 여부 검사 방법 ¤  User agent를 통해 Mobile OS 버전을 알아내서 활용 가능 n  해당 property는 read/write 가능하여 비추천 var ua = window.navigator.userAgent; Mozilla/5.0 (Linux; U; Android 2.3; en-us) AppleWebKit/999+ (KHTML, like Gecko) Safari/999.9 ¤  Modernizr※ JavaScript library 활용 (추천) n  n  csstransforms, csstransforms3d, csstransitions Android 2.1-2.3은 true이나 제대로 동작하지 않음 ※ http://www.modernizr.com: MIT&BSD licensed opens source project for HTML 5 and CSS feature detection § http://daneden.me/2011/12/putting-up-with-androids-bullshit/ single property animation 만 적용 가능
  • 73. 2D/3D Animation 73 ¨  ¨  [RULE] Animation이 수행되는 layer 수를 최소화 하고 크기를 power of 2 로 adjust 하자. Layer 수의 증가는 animation시 사용하는 GPU메모리 사용 량을 증가시킴 Open GL ES Texture 생성 제약 조건※ ¤  Texture의 width와 height는 power of 2 이어야 함 n  ¤  ¤  PowerVR chip의 PVRTC compressed image 사용시 정사각형 이어야 함: iOS d evice 계열에서 사용 http://joehewitt.com/2011/10/05/fast-animation-with-ios-webkit Max size limit 있음 n  n  ¨  2, 4, 8, 16, 32, …, 1024 OpenGL ES 1.0 SGX: 1024x1024 OpenGL ES 2.0 SGX: 2048x2048 Layer의 크기가 257x257이면 실질적으로는 512x512 크기의 texture를 생 성하게 됨 ¤  다수의 layer를 위와 같이 생성시 비효율적인 메모리 사용 증가 ※ Graphics Chip Vendor 별로 특성 확인 필요
  • 74. 2D/3D Animation 74 ¨  ¨  ¨  [RULE] Animation을 수행하는 영역은 as simple as possible 하게 유지하자 Animation 대상 block이 painting 비용 관점에서 복잡해질수록 Anim ation시 사용하는 Texture를 초기 생성하는 지연증가로 Animation 개 시 지연 발생 Not simple 의미: !(painting cost가 높음) n  CSS filter, shadow, canvas, SVG, 과도한 DOM node 개수, scaled된 image 등 일반 text 비용증가à Texture 생성 시간 증가à animation 개시 시간 증가 이해를 하고 꼭 알고 쓰자 Blurred text
  • 75. 2D/3D Animation 75 ¨  [RULE] Animation 시나리오상 animation 대상 block은 그것의 visu al change가 발생하지 않도록 작성하자 ¤  변경시 마다 texture를 재생성해야하고 texture를 caching 하여 재활용 하는 mo bile OS에서는 cache 효율성이 낮아짐 ¤  http://www.w3schools.com/css3/tryit.asp?filename=trycss3_transition2 n  width, height가 변경되는 경우와 그렇지 않은 경우 비교 Animation 도중 text blurring 시나리오 이해를 하고 꼭 알고 쓰자
  • 76. 2D/3D Animation 76 ¨  ¨  [RULE] JavaScript Library에서 제공하는 animation 효과도 mobile OS 별로 이해하고 사용하자 Android 단말에서의 page transition의 smoothness와 동작여부의 변이가 매우 심함 ¤  ¨  jQuery Mobile 1.0/Sencha Touch는 기본적으로 animation effect (flip, slide 등)을 CSS 3D transformation을 사용하여Accelerated Compositing 적용 받 으나 Platform 버전별로 성능 변이가 매우 높음 iOS 버전별, Android 버전별 성능을 확인후 사용 해야함 ¤  JS Profiling 결과를 첨부 하자
  • 77. 2D/3D Animation 77 ¨  ¨  ¨  [RULE] Compositing layer 각각은 width와 height의 제약이 있으므 로 element의 크기를 너무 크지 않게 해야한다 Unless otherwise, mobile OS의 GPU 가속 engine에서 직접 쪼개 거나 failure 발생 각 chunk를 직접 쪼개고 쪼개진 chunk 단위로 animation이 수행되도 록 한다: chunk size handling하는 webkit logic을 직접 분석 해서 포 함하자 .carousel { -webkit-transform: translate3d(0,0,0); /* or translateZ(0); */ } .carousel { -webkit-transform: translate3d(0,0,0); /* or translateZ(0); */ } .carousel-pane { -webkit-transform: translate3d(0,0,0); /* or translateZ(0); */ }
  • 78. HW 가속 Layer 이용 78 ¨  ¨  image zoom in/out시 잘 보이기 위해서 그것을 HW compositing la yer로 mapping 가능 해당 image에 아래 CSS 적용 ¤  ¨  -webkit-transform:translate3d(0,0,0) à 별도 layer에 mapping resource 사용량이 늘어남
  • 79. Canvas 2D/3D 79 ¨  ¨  [RULE] Canvas 2D는 속도가 매우 느리므로 사용을 자제 하자. 기존 HTML/CSS로 표현 불가한 것이 있을 경우 painting 속도를 충분 히 분석하고 사용하자 ¤  ¨  `12년 Canvas 2D에 대한 HW 가속이 진행중이고 성능 개선이 확인된 후에만 사 용하도록 하자 [RULE] Canvas 3D는 현시점 (`12년 1월)에서 Mobile 단말에서 미지 원이므로 사용하지 말자
  • 80. 성능 개선 Guide – Part 2 80 ¨  Parsing/Layout/Rendering
  • 81. CSS overflow property 81 ¨  ¨  [RULE] CSS의 overflow:scroll 속성의 사용은 신중히하자 div Platform 별 대처 방식 ¤  iOS에서는 two finger로 scroll 가능 n  n  ¤  Android는 one finger scroll 가능 n  ¨  -webkit-overflow-scrolling: touch iOS 5 부터 지원: native 수준 성능 제공 { width:150px; height:150px; overflow:scroll; } 3.0 이후 버전만 scroll 지원 (2.3 이하 미지원) 단점 ¤  일반 화면 scroll에 비해 속도가 느림 n  n  ¤  BackingStore에 cache 되지 않고 매번 Render Tree으로부터 다시 paint iOS 5와 Firefox는 별도의 Layer로 구성되고 layer별 BackingStore 지원으로 빠르나 메모 리 사용량 증가 poor discoverability: 사용자가 scrollable 여부 인지하기 힘듦 n  화면 자산때문에 scroll bar를 지원하지 않음
  • 82. CSS fixed positioning 82 ¨  [RULE] 꼭 필요한지 요구사항을 확인하고 browser 별 지원여부를 확인하고 사용한다 ¨  현재 mobile OS에서는 cross-platform하게 동일 UX로 제공되지 않고 있음 ¨  iScroll, Scrollability등을 사용 가능하나 성능 문제 및 잠재 defect이 존재함 ¨  http://bradfrostweb.com/blog/mobile/fixed-position/
  • 83. Layout 발생 및 비용 분석 83 ¨  ¨  [RULE] layout 발생을 최소화 하자 Layout은 전체 또는 부분 DOM traversing을 수행 후결과로 repaint를 수반 ¤  ¤  ¨  DOM tree가 커지면 layout 비용은 비례하여 증가함 ¤  ¨  Layout은 serialize된 CPU intensive 작업 Repaint는 대량의 data copy 연산 발생 야기 à battery 소진 11st (3,370개), mobile 11st (785개), latimes.com (5,563개), lemonde.fr (6,85 6개) Layout 발생 조건 ¤  ¤  ¤  ¤  ¤  Browser window resize, Orientation 변경 style information 정보 요청 DOM 변경: Adding, removing, updating nodes display property, CSS box model 값 변경 Desktop 에서의 zooming 및 scrolling n  Mobile 단말에서 layout 없이 zoom factor에 따라 content를 repaint
  • 84. Layout 비용 절감 84 ¨  ¨  [RULE] html문서와 해당 CSS loading 직후 layout에 필요한 contai ning block의 width와 height 최대한 빨리 계산 될 수 있도록 하라 Width와 height를 빨리 알리는 방법 예제 ¤  ¤  ¤  Image의 width와 height는 명시하거나, parent node를 block flow화 하라 AJAX로 HTML을 삽입시에도 삽입되는 공간을 미리 잡고 width height 명시후 bl ock flow화 하라 <div> overflow:scroll이나 auto를 사용하여 block 크기를 변경하지 않을 수 있음 à 속도 문제 발생 가능
  • 85. Layout 비용 절감 85 ¨  ¨  [RULE] 동적 또는 일시적인 정보 출력은 기존 layout을 변경을 하지 않 는 방식으로 출력하자 Layout을 변경하지 않는 문서 적재 방식 예제 ¤  기존 RenderLayer의 일부가아닌 별도의 RenderLayer가 생성되어서 화면에 ov erlay 되는 경우 n  n  ¤  ¨  Z-ordering, fixed positioning Notification, ad등에 활용 화면 상단보다는 최하단에 배치 lemonde.fr 비효율저긴 사례 ¤  Page load 완료후 DOM Node를 화면 최상단에 삽입하면서 animation 효과로 전체 페이지를 아래로 밀어 내림 n  매 animation frame 마다 전체 page layout을 수행하고, 전체 page를 repaint하는 최 악의 활용 예제
  • 86. Layout 비용 절감 86 ¨  ¨  [RULE] styling 변경은 꼭 필요시, 꼭 필요한 부분만 국소적으로 하라 Text 크기 변경, margin/padding/border 크기 변경, font type 변경등 은 전체 또는 부분 page layout 수행을 야기한다 ¤  Layout후 해당 부분은 다시 repaint를 수행 CSS Box Model ¨  Repaint 만 발생하는 경우 (layout 미 발생) ¤  Visibility, colors, transforms, backgroud images, transparency
  • 87. Repaint 비용 최소화 87 ¨  [RULE] element의 individual style을 반복적으로 변경하지 말고 cla ss name으로 일시에 변경하라 // bad var left = 10, top = 10; el.style.left = left + "px"; el.style.top = top + "px"; // better el.className += " theclassname";
  • 88. Frameset/iframe 처리 88 ¨  ¨  ¨  [RULE] Frameset, iframe와 같이 scroll bar에 의한 content scroll 을 사용하는 방식은 쓰지 말자 Mobile browser에서는 scroll bar를 미지원 Frameset/iframe은 frame 내의의 content 크기를 계산하여 키워서 도시하는 frame flattening 적용 ¤  ¨  iOS, Android, Meego Frame flattening ¤  ¤  Bug-prone 의도되지 않은 방식으로 엔진 에 의해 Layout 변경됨
  • 89. CSS 속성: -webkit-text-size-adjust 89 ¨  ¨  ¨  [RULE] iOS에서 text readability 개선을 위해 text block의 속성으로 –webkit-text-size-adjust를 활용하자 별도의 zooming이나 text 재배치 없이도 text를 읽을수 있도록 자동으 로 키워줌 (Mobile Safari only) iOS 1.0 이상에서 readability를 개선 ¤  ¨  삼성 버전 Android 지원 예정 구문 -webkit-text-size-adjust: none | auto | <percentage>; None: The text size is not adjusted. Auto: The text size is automatically adjusted for Safari on iPhone. <percentage>: The size in percentage at which to display text in Safari on iPhone.
  • 90. Image 자원 관리 90 ¨  [RULE] 최종 display 되는 크기와 일치하는 image를 사용하자 [RULE] OS별 webkit 엔진의 image cache 관리방식을 고려하여 im age의 크기를 조정하자 ¨  iOS의 image 처리 제약 조건 ¨  ¤  ¤  ¨  Decoding된 GIF, PNG, TIFF의 크기가 3MB (128MB RAM), 5MB (>256MB ) 일 경우 화면 도시 불가 JPEG는 32M pixel까지 가능하나 실질적으로는 2M pixel로 subsampling 됨 à 화질 저하 발생 성능 저하 문제 ¤  Decoding된 image의 크기가 1-3MB 이상일 경우 WebKit 내부의 decoded im age cache에 caching을 하지 않고 rendering후 cache에서 drop à 화면에 도 시할 때마다 decoding을 해야하므로 매우 성능이 나빠질 개연성 발생
  • 91. Viewport meta tag 91 ¨  ¨  [RULE] mobile site/app는 적절히 viewport를 명기하자 Viewport의 property를 적절히 setting 해야함 ¤  ¤  ¤  iOS, Tizen default width 980 pixel Desktop page는 default (980)을 사용 Mobile site/web app은 “device-width”를 사용 <meta name = "viewport" content = "width = device-width"> <meta name = "viewport" content = "initial-scale = 2.3, user-scalable = no“> http://developer.apple.com/library/IOs/#documentation/AppleApplications/Reference/SafariWebContent/UsingtheViewport/UsingtheViewport.html
  • 92. Viewport meta tag 92 Property Description width The width of the viewport in pixels. The default is 980. The range is from 200 to 10,000. You can also set this property to the constants described in “number.” Available on iPhone OS 1.0 and later. height The height of the viewport in pixels. The default is calculated based on the value of the width property and the a spect ratio of the device. The range is from 223 to 10,000 pixels. You can also set this property to the constants described in “number.” Available on iPhone OS 1.0 and later. initial-scale The initial scale of the viewport as a multiplier. The default is calculated to fit the webpage in the visible area. Th e range is determined by the minimum-scale and maximum-scaleproperties. You can set only the initial scale of the viewport—the scale of the viewport the first time the webpage is displaye d. Thereafter, the user can zoom in and out unless you setuser-scalable to no. Zooming by the user is also limit ed by the minimum-scale andmaximum-scale properties. Available on iPhone OS 1.0 and later. minimum-scale Specifies the minimum scale value of the viewport. The default is 0.25. The range is from >0 to 10.0. Available on iPhone OS 1.0 and later. maximum-scale Specifies the maximum scale value of the viewport. The default is 1.6. The range is from >0 to 10.0. Available on iPhone OS 1.0 and later. user-scalable Determines whether or not the user can zoom in and out—whether or not the user can change the scale of the viewport. Set to yes to allow scaling and no to disallow scaling. The default is yes. Setting user-scalable to no also prevents a webpage from scrolling when entering text in an input field. Available on iPhone OS 1.0 and later.
  • 93. Language encoding 93 ¨  ¨  ¨  [RULE] content의 encoding type을 반드시 명기 하자 [RULE] AJAX로 보내지는 HTML 문서도 encoding type을 반드시 명기하자 WebKit Text Encoding Source Encoding type 명기법 enum EncodingSource { ¤  HTTP header에 명기 (the best way) n  n  ¤  HTML 문서 header에 명기 n  ¨  Content-Type: text/xml; charset=ISO-8859-1 AJAX의 response header에서도 동일하게 명기 <meta http-equiv="Content-Type" content="text/html; DefaultEncoding, AutoDetectedEncoding, EncodingFromXMLHeader, EncodingFromMetaTag, EncodingFromCSSCharset, EncodingFromHTTPHeader, UserChosenEncoding, EncodingFromParentFrame } charset=utf-8“> Encoding auto-detector 단점 ¤  Auto-detector 동작 조건: n  ¤  Encoding type이 명기되어 있지 않고 && default encoding setting되어 있지 않고, paren t frame이 있지만 parent frame도 auto-detecting일 경우 auto-detector가 동작 Auto detecting algorithm은 정확하지 않고 수백 msec 수준의 지연 발생 WebKit-r103911SourceWebCoreplatformtextTextEncodingDector.h
  • 94. Language encoding 94 ¨  ¨  [RULE] 가능하면 HTTP response header에 language encoding 을 명기하라 Webkit엔진 기반 Browser는 encoding type이 알려질때까지 docum ent를 buffering ¤  HTML parsing과 Script 수행이 바로 되지 않는 지연 발생 Bytes Buffered Configuration Firefox 3.5 Chrome 3.0 IE 8 Tranfer-Encoding: chunked 1134 1056 300 Content-Type: text/html Tranfer-Encoding: chunked 204 1056 341 Content-Type: text/html Tranfer-Encoding: chunked ... <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 166 204 218 Content-Type: text/html; charset=utf-8 Tranfer-Encoding: chunked 204 280 300 http://www.kylescholz.com/blog/2010/01/performance_implications_of_charset.html http://www.w3.org/TR/REC-html40/charset.html#h-5.2
  • 95. Content Size 줄이기 95 ¨  [RULE] HTML, JS, CSS는 Minifying 하자 ¤  ¨  White space, indent, line break 제거 [RULE] gzip, deflate를 통해 compression을 하자 ¤  Gzip-friendly content 구성 방법론 n  n  n  n  ¤  CSS key-value를 가능한 동일 순서로 나열 (e.g. alphabet 순서) HTML attribute를 가능한 동일 순서로 나열 일관성 있는 casing 사용 (e.g. lowercase만 사용) 일관성 있는 quoting for HTML tag attribute (e.g. always single, always double) Gzip (deflation) 원리 n  n  Duplicated string을 찾음 두 번째 중복 string 발생시 첫번째 found string으로의 pointer로 대체 n  n  Pointer는 distance와 length의 pair 즉, 중복 string이 많아야 압출률이 높아진다
  • 96. Web에서의 Image 사용 통계 96 ¨  Image가 차지하는 비중이 63%에 이름 http://httparchive.org/interesting.php#bytesperpage
  • 97. Image Size 줄이기 (1/2) 97 ¨  [RULE] 가장 적합한 image format을 선정하자 ¤  PNG (Portable Network Graphics)는 GIF보다 압축 성능우수 n  n  ¤  ¤  10x10 pixel 정도의 작은 그림은 GIF 사용 Photographic-style image는 JPG 사용 n  ¤  ¨  Continuous tone (e.g. gradient)는 lossy compression Logo나 line art에는 GIF 사용 n  ¤  PNG는 Zip compression 압축률 > GIF는 LZW compression 압축률 GIMP “indexed”로 생성 (RGB 말고) JPG 사용시 이미지 뭉개짐 현상 발생 BMP와 TIFF는 사용하지 말라 [RULE] 추가적인 image compressor로 좀더 크기를 줄이자 ¤  Image compressor로 추가 무손실 압축 n  n  JPG: Jpegtran, jpegoptim PNG: OptiPNG, PNGOUT
  • 98. Image Size 줄이기 (2/2) 98 ¨  [RULE] 추가적인 image compressor로 좀더 크기를 줄이자 ¤  Image compressor로 추가 무손실 압축 n  n  ¨  JPG: Jpegtran, jpegoptim PNG: OptiPNG, PNGOUT [RULE] lossy compression으로 좀더 크기를 줄이자 ¤  ¤  눈에 띄는 Visual 변화 없이 크기를 줄일 수 있음 활용 tool: http://www.smushit.com/ysmush.it/ http://calendar.perfplanet.com/2011/lossy-image-compression/
  • 99. 사용되지 않는 CSS 제거 99 ¨  ¨  [RULE] 해당 페이지에서 쓰이지 않는 CSS는 제거해야 page renderi ng이 빠르게 수행된다 CSS 제거 점검 사항 ¤  ¤  현재 page에서 사용하지 앟는 inline style block을 제거 여러 page에서 공유 되는 External CSS는 작은 크기로 쪼개서 해당 page에만 적용 가능하도록 함 ¤  ¤  ¨  Page start-up 초기에 필요하지 않는 CSS는 별도의 CSS 파일로 쪽개고 “onloa d” event이후에 loading 하자 JS로 loading되는 CSS 파일의 경우도 쓰이는지 점검하자 사용되지 않는 CSS selector를 찾아주는 tool ¤  ¤  https://github.com/driverdan/cssess Bookmarklet에 JS 삽입 “cssess-min.js “ 삽입
  • 100. CSS 삽입 위치 100 ¨  ¨  [RULE] rendering 성능을 위해서 CSS, inline style block은 문서의 header에 위치 시키자 Stylesheet 위치에 따른 제약 사항 ¤  ¤  ¨  WebKit 엔진은 모든 external stylesheet을 load할 때까지 rendering을 block 함 Inline style block은 reflow를 야기해서 content를 shift 시킬 가능성이 높음 아래 webkit code에서와 같이 모든 style sheet의 적재가 끝나지 않으 면 해당 문서의 style 값 계산을 미루어 layout과 그에 따른 rendering 까지가 지연이 된다 void Document::styleSelectorChanged(StyleSelectorUpdateFlag updateFlag) { // Don't bother updating, since we haven't loaded all our style info yet // and haven't calculated the style selector for the first time. if (!attached() || (!m_didCalculateStyleSelector && !haveStylesheetsLoaded())) return;
  • 101. CSS 기능중 신중함이 필요한 기능 101 ¨  [RULE] 하기 CSS 기능은 CPU 사용률이 매우 높기 때문에 신중히 사 용하자 ¨  Rounded corners ¨  Box-shadow, Text-shadow ¤  Shadowing은 static bitmap이미지가 아니고 매번 repaint때마다 evaluate 됨 ¨  Backgroud-position ¨  Background-repeat ¨  Multiple background images Border-image ¨  Gradients ¨ 
  • 102. Rounded Corners 표현 102 ¨  [RULE] 속도를 위하여 CSS 3 specification의 border-radius, -moz -border-radius, -webkit-border-radius 신중히 사용 div { border:2px solid #a1a1a1; padding:10px 40px; background-image: url("http://img1.coupangcdn.com/image/dd/64/30/15306430_bannerList.jpg"); width:300px; border-radius:25px; -moz-border-radius:25px; /* Firefox 3.6 and earlier */ } Sample pattern
  • 103. Shadows 103 ¨  ¨  ¨  [RULE] CSS 3 specification의 text/box shadow를 신중히 사용 -webkit-box-shadow, box-shadow Shadowing 영역은 repaint 마다 매번 다시 shadowing 영역에 대한 값들을 evaluation 수행하므로 매우 비싼 연산 ¤  이미지와 같이 once decoded, reuse repeatedly가 아님 div { width:300px; height:100px; background-color:yellow; -moz-box-shadow: 10px 10px 5px #888888; /* Firefox 3.6 and earlier */ box-shadow: 10px 10px 5px #888888; border-radius:25px; background-image:url("http://img1.coupangcdn.com/image/dd/64/30/15306430_bannerList.jpg"); } ¨  Div 영역에 box-shadow시 webkit에서 scroll 성능이 느린 defect 미해결 ¤  https://bugs.webkit.org/attachment.cgi?id=80611&action=prettypatch
  • 104. Gradient 104 ¨  ¨  ¨  [RULE] –webkit-linear-gradient등은 scroll시 CPU를 지속적으로 소비하여 webkit-transfrom 기반 scroll 성능을 저하시킴으로 mobile에서는 신중히 적용 background-image: -webkit-linear-gradient(linear, left top, left b ottom, from (#666), to(#222) from jQuery Mobile의 CSS CSS gradient 소개 ¤  http://www.webkit.org/blog/1424/css3-gradients/
  • 105. <canvas> 성능 105 ¨  ¨  [RULE] HTML 5 canvas 성능은 mobile에서 매우 느리므로 사용을 하지 말자 (2012. 1) iOS 계열에서 canvas 사용시 성능 향상 tip ¤  Retina display를 사용하는 iOS에서 CSS의 하나의 pixel은 실질적으로 display 의 두 pixel을 의미 n  iOS 내부적으로 app에게는 320 pixel width로 rendering을 하게하나 이를 2배로 scal ing 하는 기능을 내포하고 있음: CPU를 통한 rescale로 늦은 것으로 예측됨 ¤  이를 역이용하여 viewport의 initial_scale를 0.5로 하여 원래 content를 작게 축 소하여 rendering을 하게 하고 이를 -webkit-transform: scale3d(2, 2, 0)로 2배 로 늘리는 방식이 더 높은 성능을 보여줌: GPU를 통한 rescaling ¤  http://29a.ch/2011/5/27/fast-html5-canvas-on-iphone-mobile-safari-perfo rmance
  • 106. DOM 관련 최적화 106 ¨  ¨  ¨  ¨  ¨  ¨  [RULE] 페이지 복잡도를 낮추어 DOM 노드의 개수를 최소화 하라 [RULE] DOM lookup 결과는 cache 하여 재사용 하라 [RULE] DOM을 manipulation하는 것을 최소화 하라 Event propagation, reflow, repaint등의 모든 연산시 DOM 노드의 개수에 비례하여 delay가 증가하게 된다 Page에 DOM node의 개수를 알려주는 tool ¤  DOM Monster 사용:http://mir.aculo.us/dom-monster/ ¤  http://stevesouders.com/mobileperf/pageresources.php DOM 개수를 줄이는 tip ¤  구체적인 사례 분석을 통해서 추가해야함
  • 107. DOM manipulation 최적화 107 ¨  ¨  [RULE] DOM을 manipulation 연산은 최소화하거나, 대상이 되는 DOM은 DOM tree에서 detach해서 변경하라 DOM 재활용 예제 ¤  ¤  ¤  ¤  ¤  ¤  ¨  Pool Elements and Objects Reuse instead of Allocate and Destroy Create a pool of DOM elements (more than you need) Use the nodes you created Release back into pool, then Go to step 2 http://www.standardista.com/velocity/#slide51 DOM manipulation 비용 최소화 방법 ¤  ¤  ¤  ¤  임시적인 변경은 documentFragment 로 보관 Update할 DOM node는 clone을 하고, 변경후에 copy하고 swap하는 방식 display:none (1 reflow, repaint)으로 제거하고, 변경을 수행, 그리고 display를 하는 방식으로 2 reflows 만 발생하게함 http://www.phpied.com/rendering-repaint-reflowrelayout-restyle/
  • 108. FE 성능 개선 Guide – Part 3 108 ¨  JavaScript
  • 109. JavaScript Engine 특징 109 ¨  V8 엔진 (Google Chrome and Android 2.3 higher) ¤  ¤  ¤  JavaScript à Machine Code (not a JIT, a compiler) Garbage collector: generational stop-the-world Crankshaft (Chrome Canary build only, ARM version under 개발) n  n  n  n  ¨  Base compiler: minimal한 최적화로 빠르게 코드 생성 Runtime profiler: 수행시간 지연 monitoring Optimizing compiler: advanced 최적화 기술 적용 및 코드 생성 Deoptimization support: SFX 엔진 (Apple iOS) ¤  ¤  JavaScript à Bytecode à Machine Code (JIT) JIT는 Browser에서만 동작 n  ¤  생성된 Native code는 Apple사에 의한 signing이 필수이나 browser에서만 예외 처리 WebView에서는 미동작: Hybrid app에서는 보안 이슈로 미지원 (추정)
  • 110. JavaScript Loading Sequence 110 ¨  Web browser가 Document object를 생성하고 parsing을 개시 ¤  ¤  ¨  Element와 Text Node를 document에 추가 Document.readyState는 “loading”로 set Tag parsing 계속 ¤  “async”나 “defer” attribute를 갖지 않는 <script> tag를 만나면 n  n  ¤  “async”나 attribute를 갖는 <script> tag를 만나면 n  n  ¨  element를 삽입하고 synchronous하게 실행함 Download하고 실행시까지 parsing은 stop and wait Download를 개시하고 parsing 계속 해당 script가 도착할때마다 실행하고 순서는 지켜지지 않음 Tag parsing 완료시 ¤  ¤  readyState는 “intractive”로 set “defer” attribute가 set된 모든 <script>를 순차적으로 실행 JavaScript: The Definitive Guide
  • 111. JavaScript Loading Sequence 111 ¨  Parsing을 완료후 DOMContentLoaded event를 fire ¤  ¤  ¨  이 시점에 “async” attribute로 set된 script block이 여전히 실행되지 않고 있을 수 있음 “defer” attribute로 set된 script block은 실행 완료 readyState가 “complete”로 set 됨 ¤  ¤  ¨  모든 resource (image등)의 download가 완료 모든 “async” attribute로 set된 script block의 download 및 실행 완료 User input에 대해 event handler가 asynchronous하게 실행 JavaScript: The Definitive Guide
  • 112. JavaScript 실행 제약 112 ¨  ¨  [RULE] JavaScript의 수행은 main thread의 block을 야기하므로 최대한 짧 게 수행되도록하라 JavaScript 수행동안 UI refresh 가 되지 않음 ¤  ¤  ¨  iOS에서의 JavaScript 실행 제약 조건 ¤  ¤  ¨  Scheduling, preemption, multiplexing 되지 않음 Chrome, WebKit2는 multi-process 도입으로 해당 사항 없음 수행 시간이 5초가 넘어가면 수행 중지 사용하는 Memory가 10MB가 넘어갈 경우 수행 중지 기존의 Task 쪼개기 방식 ¤  ¤  setTimeOut, setInterval을 통해 쪼개서 작업 XMLHttpRequest로 asynchronous 하게 처리
  • 113. Web Worker Thread 사용 (1/2) 113 ¨  HTML 5의 Web worker thread ¤  JavaScript의 Concurrency 제약을 극복하기 위한 HTML 5 기능 Background에서 JavaScript를 수행하게 하고, message passing mechanis m을 제공함 ¤  Worker thread는 DOM 접근이 되지 않고 message posting만 사용 해야함 ¤  ¨  Web worker 사용예 Main var worker = new Worker('doWork.js'); // worker 생성, 별도 file로 수행할 JS 파일 contain worker.addEventListener('message', function(e) { console.log('Worker said: ', e.data); }, false); worker.postMessage('Hello World'); // start by sending data to our worker. doWork.js self.addEventListener('message', function(e) { self.postMessage(e.data); }, false); http://www.whatwg.org/specs/web-apps/current-work/multipage/workers.html
  • 114. Web Worker Thread 사용 (2/2) 114 ¨  Web worker thread는 multi-threaded 특징 때문에 JavaScript 기 능의 subset 만을 접근 가능함 ¤  접근 가능 n  n  n  n  n  n  ¤  Navigator object 접근 가능 Location object read-only로 접근 가능 XMLHttpRequest 사용 가능 setTimeout/clearTimeout(), setInterval/clearInterval() External script를 importScripts()로 import 또 다른 web worker thread 생성 접근 불가능 n  n  n  n  DOM access Window object Document object Parent object http://www.html5rocks.com/en/tutorials/workers/basics/
  • 115. JavaScript Timer 동작 115 ¨  [RULE] SetTimeout 와 setInterval의 동작의 차이점을 이해하고 사용 하라. ¤  ¤  JavaScript code는 one piece of code at a time으로 실행 미실행 Asynchronous JavaScript event queue에 쌓이고 sequential 하게 수 행됨
  • 116. requestAnimationFrame (1/2) 116 ¨  ¨  [RULE] JavaScript로 animation을 하고자 할 경우 timer를 사용하지 말고 requestAnimationFrame을 사용하라 WebKit 엔진 및 Native Platform의 Rendering 시스템상에서 최적의 animation frame 생성 시점 도달시 제공된 API에 의해 등록된 Callba ck을 호출 ¤  Mobile OS 별로 화면 갱신 방식의 차이가 있음 n  n  n  ¨  vsync를 사용하는 system은 실제 LCD screen buffer로의 복사 frequency가 해당값 에 제약 받음 vsync 60 fps system은 JavaScript 수준 animation에서 그것을 초과하는 frame rat e을 구현할수 없음 e.g.) 60 fps시스템 à 60/sec로 호출 best effort, not guaranteed 지원 시스템 ¤  ¤  Safari, Chrome, Firefox Mobile에서는 도입 예정
  • 117. requestAnimationFrame (2/2) 117 ¨  사용시 장점 ¤  동시에 발생하는 각종 animation을 browser 수준에서 최적화 할수 있음 n  n  ¤  JS animation과 CSS transition을 synchronize 가능함 e.g.) 한번의 reflow나 repaint로 화면을 최종 화면을 구성 Invisible한tab에 위치한 animation은 호출 되지 않음 n  ¨  CPU, GPU 사용 및 메모리 사용을 줄여 battery 효율적인 동작이 가능함 사용 예제 https://gist.github.com/1579671 // shim layer with setTimeout fallback window.requestAnimFrame = (function(){ return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function( callback ){ window.setTimeout(callback, 1000 / 60); }; })(); // usage: // instead of setInterval(render, 16) .... (function animloop(){ requestAnimFrame(animloop); render(); })(); // place the rAF *before* the render() to assure as close to // 60fps with the setTimeout fallback.
  • 118. CSS property 접근 118 ¨  [RULE] JavaScript를 통한 CSS Property의 접근은 page loading 이 완료된 시점에서 하자. ¤  ¨  E.g. onload event후 Page loading 중 CSS property 접근시 문제점 ¤  JavaScript를 통한 CSS property의 접근은 WebKit에서 가장 비싼 연산인 layo ut() 강제함: 수백 msec도 소요 가능성 있음 ¤  WebKit 엔진: Pending되어있는 CSS stylesheet를 무시하고 layout후에 해당 값을 돌려준다 ¤  기타 Browser: CSS가 완전히 loading 될때까지 JavaScript를 suspension 시 키거나 // FIXME: This is a bad idea and needs to be removed eventually. // Other browsers load stylesheets before they continue parsing the web page. // Since we don't, we can run JavaScript code that needs answers before the // stylesheets are loaded. Doing a layout ignoring the pending stylesheets // lets us get reasonable answers. The long term solution to this problem is // to instead suspend JavaScript execution. void Document::updateLayoutIgnorePendingStylesheets() { CSS property 접근시 수행되는 WebKit 내부 함수
  • 119. JavaScript loading 최적화 (1/6) 119 ¨  ¨  [RULE] HTML 문서 적재 시점까지 호출되지 않는 JavaScript function의 lo ading은 미루자 Script 수행 철칙: 어길 시 수행 결과의 correctness를 깨트림 ¤  ¤  ¨  “Script Execute In Order” “Script Execute after fully loading all stylesheets” JavaScript loading 방식: <script src =“file.js”> 및 inline JavaScript는 H TML parsing, page rendering을 block 시킴 ¤  HTML parsing 도중 inline 또는 external JavaScript를 만나면 n  n  ¤  Inline JavaScript는 parsing후 호출이 되었으면 실행 External JavaScript는 network을 통해 적재, parsing후 호출이 되었으면 실행 Loading,parsing, 실행중 계속적인 HTML parsing은 suspend가 기본 동작 n  Webkit에서는 속도 향상을 위해 image object는 speculative하게 loading을 수행 n  ¤  https://bugs.webkit.org/show_bug.cgi?id=17480 (WebKit PreloadScanner) 이는 JavaScript의 수행으로 DOM 변경이 가능하므로 JavaScript의 수행 완료가 보 장되어야만 하기 때문임
  • 120. JavaScript loading 최적화 (2/6) 120 ¨  JavaScript의 loading에 의한 suspend를 최소화 하는 것이 전체 pag e loading 성능 개선이 필수적임 ¤  ¨  Deferring 방법 ¤  ¤  ¤  ¨  Page startup 동안 꼭 필요한 JavaScript를 제외하고, page startup 이후로 def erring “defer” attribute 정의 “async” attribute 정의 JavaScript 실행이 필요한 시점이 되서야 load 되도록 program 작성 Deferring 장점 ¤  ¤  ¤  초기 download size 줄어듦 다른 resource (image, CSS)가 병렬로 load 가능 Startup 시점까지 꼭 필요한 JavaScript만이 load되고 compile되어서, 궁극적으 로 rendering time 빨라짐
  • 121. JavaScript loading 최적화 (3/6) 121 ¨  defer attribute 사용 ¤  ¨  async attribute 사용 ¤  ¨  <script defer src="siteScript.js" onload="myInit()"></script> async 와 defer의 공통점 ¤  ¤  ¨  <script src="script.js" type="text/javascript" defer="defer"></script> Parser를 멈추지 않고 해당 script download를 즉시 시작함 Optional onload handler에서 initialization 수행 async 와 defer의 차이점 ¤  ¤  async는 download가 끝나는 시점과 window load event 전에 실행됨 defer는 async와 동일하나 defer된 순서를 지켜서 수행하고 parsing이 끝나는 시점에서 DOM ContentLoaded event 발생전까지 수행됨 n  DOMContentLoaded n  n  n  Window load n  ¨  해당 page의 document parsing이 완료되고, 즉 DOM tree 가 완성시 fire Referenced stylesheet, image, subframe 적재는 안끝날수도 있음 Subresource까지의 loading이 끝났을때 발생 두개 모두 지정시: async attribute 특성으로만 동작 http://davidwalsh.name/html5-async
  • 122. JavaScript loading 최적화 (4/6) 122 ¨  Programmer driven 최적화 ¤  ¨  JavaScript module 화 ¤  ¨  JavaScript의 module 화 및 lazy loading 기능 block 별로분리하고 onload 전과 후, 그리고 실제 호출 시점에 loading 가능하도 록함 Lazy loading 적용 사례 ¤  Script as DOM <script type="text/JavaScript"> function loadFile(url) { var script = document.createElement('SCRIPT'); script.src = url; document.getElementsByTagName('HEAD')[0].appendChild(script); } </script> ¤  ¤  XmlHttpRequest (XHR) /* */ comment block안에 JS를 넣어두면 network loading은 하나 parsing은 하지 않는다. 후에 unstrip을 하고 eval을 통해서 parsing함 n  http://googlecode.blogspot.com/2009/09/gmail-for-mobile-html5-series-reducing.ht ml
  • 123. JavaScript loading 최적화 (5/6) 123 ¨  WebKit이 HTMLDocumentParser의 동작 ¤  external script의 download, 실행 완료까지 HTMLDocumentParser가 block n  ¤  ¨  Block에 의한 page loading 및 rendering 속도 저하 심각 WebKit PreloadScanner ¤  HTMLDocumentParser가 block 되는 동안 미리 download 가능한 subresour ce (CSS, JS)가 있는지를 speculatively하게 scan 하여 download 개시 n  ¨  CSS나 기타 resource는 HTMLDocumentParser를 block 시키지 않음 https://bugs.webkit.org/show_bug.cgi?id=17480 (WebKit PreloadScanner) PreloadScanner 동작 조건 (Browser 별로 실험 필요) ¤  <head>내에 defer, async가 없을 경우 <body>내의 script 를 preload http://gent.ilcore.com/2011/01/webkit-preloadscanner.html
  • 124. JavaScript loading 최적화 (6/6) 124 ¨  PreloadScanner의 제약사항 ¤  Scanning 되지 않는 subresource n  ¤  ¤  ¤  ¤  iframe, @import stylesheet, fonts, HTML5 audio/video, <head>에서 block 되면 <body>는 scan 하지 않음 <xhtml>에서 미동작 PreloadScanner에서 생성한 token을 HTMLDocumentParser에서 재활용하 지 않음 External stylesheet는 완전히 download 되기 전까지 scan 되지 않음 http://gent.ilcore.com/2011/01/webkit-preloadscanner.html
  • 125. document.write() 사용 제한 125 ¨  ¨  [RULE] 필요한 resource는 HTML markup 으로 직접 정의하라 아래와 같이 loading시 document.write를 부른 js와 second.js가 모 두 loading 될 때까지 blocking 됨 document.write('<script src="second.js"></script>'); http://www.whatwg.org/specs/web-apps/current-work/multipage/parsing.html
  • 126. CSS @import 제약사항 126 ¨  ¨  [RULE] <link> tag를 사용하여 CSS를 load하고 CSS @import를 사용하지 말아라 Browser는 일반적으로 import 된 stylesheet을 병렬 loading을 지원 하지 않음
  • 127. Third party script 통합 127 ¨  [RULE] Third party script의 loading은 async로 설정하여 onload 이후에 load 및 실행하도록 하자 ¤  </body> 직전에 삽입도 가능 ¨  Top e-commerce site는 평균 7개를 포함하고, 25개까지 포함 ¨  Popular third party JS ¤  ¤  ¤  ¤  ¤  Facebook Like button Google Plus button (http://www.google.com/webmasters/+1/button/) Twitter Share & Follow button (they require the same JS file) Twitter Tweet Box Google Analytics n  GA는 async로 설정하는 field를 제공함 http://www.aaronpeters.nl/blog/why-loading-third-party-scripts-async-is-not-good-enough
  • 128. FE 성능 개선 Guide – Part 4 128 ¨  DOM Event
  • 129. DOM Event 지원 및 호환성 129 ¨  Mobile browser compatibility 이슈 ¤  ¨  Mouse가 없는 Touch Screen 장치의 특징 때문에 User Interaction과 관련이 있는 DOM event들의 호환성의 차이가 mobile OS 별로 발생 Major difference ¤  Mouse 부재에 따른 mouse event emulation n  Mouse event 자체, 이와 연관되 form/document 이벤트 동작 호환성 상이 n  ¤  mousemove, mouseout, :hover, blur, focus 등 Touch 전용 event 정의 n  iOS에서는 native 및 JavaScript에서 사용 가능하도록 통일하여 지원중 n  n  n  iOS UIEvent n  http://developer.apple.com/library/safari/#documentation/UserExperience/Refere nce/TouchEventClassReference/TouchEvent/TouchEvent.html iOS Safari JavaScript Object n  http://developer.apple.com/library/IOs/#documentation/AppleApplications/Refere nce/SafariWebContent/HandlingEvents/HandlingEvents.html#//apple_ref/doc/uid/ TP40006511-SW1 현재 널리 채택되어 사용되고 있음
  • 130. iOS User Interaction Guide 130 ¨  Browser vendor 및 Platform 별로 호환성이 차이 분석 ¤  iOS상 click 동작: clickable element에서의 click시 아래의 순서로 발생 n  n  ¤  mouseoveràmousemoveàmousedownàmouseupàclick mouseout: clickable에서 click후 다른 clickable element를 click할 때만 발생 iOS상 scroll 동작 n  Pan 동작 완료 시점에 1회 발생
  • 131. iOS 지원 Event 현황 131 Event abort blur change click copy cut drag drop focus gesturestart gesturechange gestureend load mousemove mousedown mouseup mouseover mouseout orientationchange pagehide pageshow paste reset selection submit touchcancel touchend touchmove touchstart unload Generated Yes Yes Yes Yes No No No No Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes No Yes No Yes Yes Yes Yes Yes Yes Conditional No No No Yes N/A N/A N/A N/A No N/A N/A N/A No Yes Yes Yes Yes Yes N/A No No N/A No N/A No N/A N/A N/A N/A No Available iOS 1.0 and later. iOS 1.0 and later. iOS 1.0 and later. iOS 1.0 and later. iOS 1.0 and later. iOS 2.0 and later. iOS 2.0 and later. iOS 2.0 and later. iOS 1.0 and later. iOS 1.0 and later. iOS 1.0 and later. iOS 1.0 and later. iOS 1.0 and later. iOS 1.0 and later. iOS 1.1.1 and later. iOS 4.0 and later. iOS 4.0 and later. iOS 1.0 and later. iOS 1.0 and later. iOS 2.0 and later. iOS 2.0 and later. iOS 2.0 and later. iOS 2.0 and later. iOS 1.0 and later. http://developer.apple.com/library/IOs/#documentation/AppleApplications/Reference/SafariWebContent/HandlingEvents/HandlingEvents.html#//apple_ref/doc/uid/TP40006511-SW1
  • 132. Touch event 132 ¨  ¨  [RULE] touch screen device에서 사용자 touch에 의한 content의 p anning은 touch event를 사용하라 Mouse/wheel event 사용시 conflict 발생 가능 ¤  ¨  Bluetooth mouse가 touch screen과 같이 쓰이는 configuration에서 그것들을 구분하여 처리할 수 있음 Apple이 제안한 touch event touchstart: Happens every time a finger is placed on the screen touchend: Happens every time a finger is removed from the screen touchmove: Happens as a finger already placed on the screen is moved across the screen touchcancel: The system can cancel events, node.ontouchstart = function(evt){ console.log(evt.pageX + "/" + evt.pageY); // OH NO! These values are blank, this must be a bug }
  • 133. Event 사용 제약 133 ¨  ¨  [RULE] DOM Level 2의 mouse event는 지원 여부 및 동작 방식을 Platform별로 확인 후 사용 [RULE] onclick 이벤트의 경우 생성시 300-500msec delay가 발생 가능하므로 즉시 발생이 필요한 경우 touch event를 사용하라 ¤  ¨  데모 동작 확인: http://pcapperf.appspot.com/fastbutton [RULE] onscroll은 1회만 발생하므로 desktop에서의 mousemove 와 같은 연산의 ontouchmove (touch event)를 사용하라
  • 134. Fast button 제작 134 ¨  ¨  browser의 onclick event는 double tap/panning 등의 처리로 지연 ( e.g. 300msec iOS)를 포함하고 이는 game에서와 같이 빠른 respon se를 필요로 하는 web app 개발시 제약임 onTouchStart는 지연없이 동작 ¤  <div ontouchStart=“doSomething()”> 구성 가능하나 누르는 순간 발생 ¤  onTouchEnd에서 발생시켜서 onclick을 emulation http://cubiq.org/remove-onclick-delay-on-webkit-for-iphone http://code.google.com/intl/ko-KR/mobile/articles/fast_buttons.html
  • 135. Touch 기반 Fast Button 예제 1 135 function NoClickDelay(el) { this.element = typeof el == 'object' ? el : document.getElementById(el); if( window.Touch ) this.element.addEventListener('touchstart', this, false); } NoClickDelay.prototype = { handleEvent: function(e) { switch(e.type) { case 'touchstart': this.onTouchStart(e); break; case 'touchmove': this.onTouchMove(e); break; case 'touchend': this.onTouchEnd(e); break; } }, onTouchStart: function(e) { e.preventDefault(); this.moved = false; this.theTarget = document.elementFromPoint(e.targetTouches[0].clientX, e.targetTouches[0].clientY); if(this.theTarget.nodeType == 3) this.theTarget = theTarget.parentNode; this.theTarget.className+= ' pressed'; this.element.addEventListener('touchmove', this, false); this.element.addEventListener('touchend', this, false); }, onTouchMove: function(e) { this.moved = true; this.theTarget.className = this.theTarget.className.replace(/ ?pressed/gi, ''); }, onTouchEnd: function(e) { this.element.removeEventListener('touchmove', this, false); this.element.removeEventListener('touchend', this, false); if( !this.moved && this.theTarget ) { this.theTarget.className = this.theTarget.className.replace(/ ?pressed/gi, ''); var theEvent = document.createEvent('MouseEvents'); theEvent.initEvent('click', true, true); this.theTarget.dispatchEvent(theEvent); } this.theTarget = undefined; } };
  • 136. Google Clickbuster 136 google.ui.FastButton = function(element, handler) { this.element = element; this.handler = handler; element.addEventListener('touchstart', this, false); element.addEventListener('click', this, false); }; google.ui.FastButton.prototype.handleEvent = function(event) { switch (event.type) { case 'touchstart': this.onTouchStart(event); break; case 'touchmove': this.onTouchMove(event); break; case 'touchend': this.onClick(event); break; case 'click': this.onClick(event); break; } }; google.ui.FastButton.prototype.onTouchStart = function(event) { event.stopPropagation(); this.element.addEventListener('touchend', this, false); document.body.addEventListener('touchmove', this, false); this.startX = event.touches[0].clientX; this.startY = event.touches[0].clientY; }; google.ui.FastButton.prototype.onTouchMove = function(event) { if (Math.abs(event.touches[0].clientX - this.startX) > 10 || Math.abs(event.touches[0].clientY - this.startY) > 10) { this.reset(); } }; google.ui.FastButton.prototype.onClick = function(event) { event.stopPropagation(); this.reset(); this.handler(event); if (event.type == 'touchend') { google.clickbuster.preventGhostClick(this.startX, this.startY); } }; google.ui.FastButton.prototype.reset = function() { this.element.removeEventListener('touchend', this, false); document.body.removeEventListener('touchmove', this, false); }; google.clickbuster.preventGhostClick = function(x, y) { google.clickbuster.coordinates.push(x, y); window.setTimeout(google.clickbuster.pop, 2500); }; google.clickbuster.pop = function() { google.clickbuster.coordinates.splice(0, 2); }; google.clickbuster.onClick = function(event) { for (var i = 0; i < google.clickbuster.coordinates.length; i += 2) { var x = google.clickbuster.coordinates[i]; var y = google.clickbuster.coordinates[i + 1]; if (Math.abs(event.clientX - x) < 25 && Math.abs(event.clientY - y) < 25) { event.stopPropagation(); event.preventDefault(); } } }; document.addEventListener('click', google.clickbuster.onClick, true); google.clickbuster.coordinates = [];
  • 137. Double tap 대응 137 ¨  ¨  [RULE] double tap시 browser 별 동작 조건을 고려해서 object를 배 치 하자 iOS상 double tap for zooming ¤  ¨  Android상 double tap for zooming ¤  ¨  <div>, <ol>, <ul>, <table>, <img> element를 찾고 해당 element가 block일 경우 content를 화면 크기에 fitting 시키고 중앙으로 이동 Double tap 된 부분을 기준으로 특정 zoom level로 확대나 축소 Samsung Android 상 double tap for column zooming ¤  <p> <article>등의 block 일 경우 device width로 content를 layout하여 displa y 해줌
  • 138. FE 성능 개선 Guide – Part 5 138 ¨  Networking/Caching/Loading
  • 139. DNS Prefetch 139 ¨  ¨  [RULE] 명시적으로 이동할 link는 DNS prefetch 를 사용하라 Chrome Browser 지원 <link rel="prefetch" href="http://www.example.com/">
  • 140. LocalStorage 사용 140 ¨  ¨  ¨  [RULE] 변경이 자주 되지 않은 content는 client-side cache에 저장 되도록 하거나, localStorage에 명시적으로 저장하여 network reques t 발생 최소화 하자 http://dev.w3.org/html5/webstorage/ google.com 활용 예 ¤  JavaScript와 CSS를 저장후 재방문시 사용: 130 entry로 저장 mres.-8Y5Dw_nSfQztyYx: <style>a{color:#11c}a:visited{color:#551a8b}body{margin:0;pad... mres.-Kx7q38gfNkQMtpx: <script> //<![CDATA[ var Zn={},bo=function(a,b){b&&Zn[b]||(ne... mres.0kH3gDiUpLA5DKWN: <style>.zl9fhd{padding:5px 0 0}.sc59bg{clear:both}.pyp56b{tex... mres.0thHLIQNAKnhcwR4: <style>.fdwkxt{width:49px;height:9px;background:url("data:ima... mres.36ZFOahhhEK4t3WE: <script> //<![CDATA[ var kk,U,lk;(function(){var a={};U=funct... mres.3lEpts5kTxnI2I5S: <script> //<![CDATA[ var Ec,Fc,Gc=function(a){this.Jl=a},Hc="... mres.4fbdvu9mdAaBINjE: <script> //<![CDATA[ u("_clOnSbt",function(){var a=document.g... mres.5QIb-AahnDgEGlYP: <script> //<![CDATA[ var cb=function(a){this.Cc=a},db=/s*;s... mres:time.-8Y5Dw_nSfQ...: 1301368541872 mres:time.-Kx7q38gfNk...: 1301368542755 mres:time.0kH3gDiUpLA...: 1301368542257 mres:time.0thHLIQNAKn...: 1301368542223 mres:time.36ZFOahhhEK...: 1301368542635 mres:time.3lEpts5kTxn...: 1301368542579 mres:time.4fbdvu9mdAa...: 1301368542720 mres:time.5QIb-AahnDg...: 1301368542856 http://calendar.perfplanet.com/2011/localstorage-read-performance/
  • 141. RTT 최소화 141 ¨  [RULE] external CSS나 external JS 파일은 수를 최소화 하라 [RULE] image는 CSS Sprite로 파일의 수를 줄여라 ¨  CSS Sprite 서비스 ¨  ¤  ¤  ¨  Image중 항상 같이 load 되거나, 동적으로 변경되지 않은 것을 한 개의 image로 묶음 http://spriteme.org/ Sprite한 image의 format이 JPEG일 경우 sub-sampling에 의한 im age 왜곡이 심각하게 발생할 수 있으니 최대 size를 넘지 않도록 정해야 함 ¤  iOS는 2MB
  • 142. CSS와 JS 파일 Ordering 최적화 142 ¨  ¨  ¨  [RULE] external CSS는 가능하면 external JS 이전에 배치하라 [RULE] inline script는 가능하면 외부 자원이후에 배치하라 JavaScript는 DOM을 변경가능하므로 JavaScript를 만나면 downlo ad해서 실행할 때까지 다른 자원의 parallel loading을 block함
  • 143. Combine external JavaScript 143 ¨  ¨  [RULE] external JavaScript의 수를 줄여라 [RULE] JavaScript는 기능 단위 module 분리하고 실행하라 ¤  ¤  ¤  <head>내의 JavaScript file의 수를 최소화 하라 잘 방문하지 않는 site의 JavaScript는 해당 page가 열릴때만 download 받게 하 라 ¤  ¨  Page startup에 필요한 minimal code와 page load후에 필요한 부분 두개로 나 누어라 작은 양의 JavaScript code는 HTML에 inlining 하는 것을 고려하라 즉, page load 전과 후에 필요한 큰 file 두개로 나누어서 관리 하도록 하자