211
Mobile Web Application 개발 방법론: 설계, 구현 최적화 Guide 임상석 Manager [email protected] SD 개발팀, 플랫폼 기술원 1

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

Embed Size (px)

DESCRIPTION

The deck includes a set of techniques and knowledge that can be used when you try to optimize the performance HTML5 app, mobile Web site, JavaScript application running on top of a browser or WebView

Citation preview

Mobile Web Application 개발 방법론: 설계, 구현 및 최적화 Guide

임상석 Manager [email protected] SD 개발팀, 플랫폼 기술원

1

자료 목적

대상: 실무 Web App 개발자 및 개발 과제 Project Lead

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

2

Contents

¨  Mobile Web Application 정의

l  Server-hosted, Hybrid

¨  Mobile Web Application SW Architecture 설계 사례

l  UI/UX 개발: jQuery, jQuery Mobile

l  Audio 기능 개발: Sound Manager2

l  Fragmentation handling: Modernizr

l  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

3

HTML5 Mobile Web App 전망

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)

4

HTML5 Web App 기술 분야

ss

Algorithm Native API

Java/C++/Objective C

Compiling

HTML5

CSS3.0 CSS2.1

JavaScript (system/module/logic)

HTML4 Flash

DOM JavaScript (DHTML)

SW 개발자 (Programming)

Web designer (Publishing)

HTML5/Web App 개발자 (Programming)

HW 최적화

ARM GPU Browser

5

Mobile Web Application 분류

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

l  Server hosted (except for App cache, Local Storage )

l  Hybrid (packaged and locally installed)

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

Android/iOS

Browser

WebView (WebKit)

HTML5 App

Remote Server

On target device

Android/iOS

WebView (WebKit)

HTML5 App

Android/iOS

Native Web App

WebView (WebKit)

Web Data Web Data

Container/Binder (PhoneGap, AppMobi)

Web Data

Binder

Native Part

6

App Store로부터 Runaway

¨  App Store 통제

l  run/own/censor ed by platform/OEM/carrier

l  Sale/in-app billing commission

¨  시장 예: runaway from app store, into browser

l  Amazon -  Offline access, cloud sync, Native app look&feel GUI

l  Facebook

-  App center strategy -  W3C community group for browser fragmentation and billing

l  Financial Times

-  Offline access, Native app look&feel GUI -  Auto download

7

8

주요 Factor 고려 사항

서비스 유형

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

Device 호환성 Multi- Platform/Device 대상인 경우 Web App이 적합함

Data provision 방식

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

Client-based

HTML 5만으로 client 구현 가능한 경우 1)  Web 기반 client를 개발해야 하는 비용 발생 2)  간단한 App들이 이 범주에 속함

Native component를 사용해야만 하는 경우

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

Performance-constraint

1)  기본적으로 Web App은 data loading, parsing, rendering 의 구조이기 때문에 Native 대비 성능이 느릴 수 밖에 없음 2)  Hybrid 방식으로 Native component와 WebView 사이의 Data 전송이 발생하게 되면 Data 복사에 따른 추가의 overhead 발생

Ex) Device API 호출 시 overhead 발생 1)  최적화되지 않은 기능을 많이 사용하면 안됨

Ex) Vector Graphic 위해 Canvas 2D를 많이 사용하면 성능이 저하됨

Native to Web 이전 검토시 고려사항

시장 사례 분석

¨  Melon 사례

l  Server hosted: m.melon.com, t.melon.com

l  Hybrid: iOS 및 Android app

¨  11번가 사례

l  Server hosted: m.11st.co.kr

l  Hybrid: iOS 및 Android app

9

Web App 개발 요구사항

¨  본 강좌에서 가정하는 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 개발에도 재활용이 가능해야함

10

Web App 개발 요구사항: cross-platform

11

UI 상세 명세서 일부

¨  아래의 3분류의 화면 Template 제공하고 화면간 이동 및 이동시 transition effect를 지원 해야함

¨  노래 목록은 위 아래 scroll이 가능해야하고 이때 상단 및 하단 메뉴는 화면에 고정 되어있어야 함

고정

고정

화면 전환 및 효과

화면 전환 및 효과

12

Web App SW Arch. 구성 예

¨  Open source기반 Web application SW 구조

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

¨  Open source 선택시 필수 고려사항

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

l  License 종류, 회사 편향도

Android/iOS/Blackberry OS/Kindle Fire

Browser WebView (WebKit)

DOM (Document Object Model)

Application processor, GPU

jQuery + plug-in

jQuery Mobile + plug-in Sound Manager2 Modernizr Fast

Button iScroll

(JS Scroller)

HTML5 audio application

URL Bar

Handler

UI Framework

Audio FW

Fragmentation Handling

13

Page Speed: Mobile 11번가 14

jQuery Mobile (JQM)

¨  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/

15

JQM Pagination

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

¨  개별 HTML에 저장된 page를 load하는 방식에 비해 속도, 데이터 공유를 위해서 필수적인 기법

16

<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

¨  지원하는 widgets

l  Pages, dialogs, toolbars, listview, button, form element, accordion, collapsibles

17

Listview 예제 <!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>

18

Navbar 추가

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

</div><!-- /footer -->

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

</div><!-- /header --> 상단 고정

하단 고정

19

Multi page template <body> <!-- Start of first page --> <div data-role="page" id="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 href="#bar" data-transition="pop">bar</a></p> </div><!-- /content -->

<div data-role="footer"> <h4>Page Footer</h4> </div><!-- /footer -->

</div><!-- /page --> <!-- Start of second page --> <div data-role="page" id="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" data-transition="slide">Back to foo</a></p> </div><!-- /content -->

<div data-role="footer"> <h4>Page Footer</h4> </div><!-- /footer -->

</div><!-- /page --> </body>

Page foo

Page bar

pop slide

20

External page handling (1/2)

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

l  <head> 내부 부분 parsing 하지 않음 -  JS 파일, <script> block, CSS를 load 하지 않음

l  Page-specific JavaScript 및 CSS는 직접 loading 해야함 -  Page div 내에 포함

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

<!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

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

main.html

21

External page handling (2/2)

¨  Page prefetching

l  external page를 전환 속도 개선을 위해 prefetch

¨  DOM size 자동 관리

l  숨겨진 page (pagehide event)의 DOM을 detach 후 제거 à memory 사용량 개선 기능

l  show시 자동으로 AJAX를 통해 다시 load함

¨  Page를 DOM에 caching 하는 기능

l  hide시 DOM에서 detach후 해당 page를 별도로 cache

<a href="prefetchThisPage.html" data-prefetch> ... </a> programmatically load 방식 $.mobile.loadPage( pageUrl, { showLoadMsg: false } );

22

<div data-role="page" id="cacheMe" data-dom-cache="true">

Web based WISWYG Editor

¨  Codiqa l  GUI editor

¨  ThemeRoller Mobile l  Theme editor

ThemeRoller Mobile

Codiqa (charged)

23

UI 명세서 중간 점검

¨  JQM widget set 구성으로 구현 가능

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

고정

고정

화면 전환 및 효과

화면 전환 및 효과

24

HTML5 Data- attribute

¨  data-* attribute 추가 l  Custom attribute 정의하여 사용 가능

¨  저장값 접근 방식

l  JavaScript/DOM API 활용

l  Jquery

l  Jquery Mobile

<li id="appDeveloperInfo"class="user" data-name="sangseok" data-company="SK planet" data-lang="korea" data-food="Noodle"> <span>고맙습니다</span> </li>

var appDeveloperInfo = document.getElementById(‘appDeveloperInfo’); var appDeveloperName = appDeveloperInfo.getAttribute(‘data-name’);

$("li:jqmData(role=’name’")

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

25

JQM Data- attribute

¨  JQM은 HTML 5 Data- attribute를 Widget 마다 정의하여 사용 l  data-role, data-inset, data-position, data-corner, data-dom-cache

l  http://jquerymobile.com/demos/1.1.0/docs/api/data-attributes.html

¨  JQM의 data enhance

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

-  Extra markup 추가 -  새로운 CSS class 적용 -  Event handler 등록

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

l  data-enhance=``false’’

26

JQM Event (1/2)

¨  Touch event

l  tap, taphold, swipe, swipeleft,swiperight

¨  Virtual mouse events

l  vmouseover, vmousedown, vmousemove, vmouseup

l  vclick, vmousecancel

¨  Orientation change

l  orientationchange

¨  Scroll events

l  scrollstart, scrollstop

27

JQM Event (2/2)

¨  Page load events

l  pagebeforeload, pageload, pageloadfailed

¨  Page change events

l  pagebeforechange, pagechange, pagechangefailed

¨  Page transition events

l  pagebeforeshow, pagebeforehide, pageshow, pagehide

¨  Page initialization evets

l  pagebeforecreate, pagecreate, pageinit

¨  Layout events

l  updatelayout

28

JQM Event Binding

¨  jQuery의 live() 또는 bind() 를 사용

l  live(): jQuery selector에 현재 또는 미래에 match되는 모든 element에 event handler를 attach

l  bind():jQuery selector에 현재 match되는 모든 element에 event handler를 attach

l  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); });

29

JQM Method

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

l  $.mobile.changePage

l  $.mobile.loadPage: external page load

l  $.mobile.fixedToolbars.hide

l  $.mobile.silentScroll -  주어진 Y위치로 onscroll trigger하지 않고 scroll

l  $.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

});

30

JQM VS Sencha Touch (1/2)

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

31

JQM VS Sench Touch (2/2)

<body> <div data-role="page" id="sub" data-add-back-btn="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' } }] });

<head> js파일 include

</head> <head>

jQuery Mobile Sencha Touch

32

UI 명세서 중간 점검

¨  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를 기준으로 위치를 고정

33

CSS position:fixed issue

¨  CSS position:fixed 정의

l  element의 위치를 containing block이 아닌 window를 기준점으로 위치를 정함

l  Web page 를 scroll하여도 위치가 고정되어 각종 메뉴구성에 쓰임

¨  CSS position fixed 구현 방식

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

l  Android 2.2 이하 오동작

-  window기준으로 첫번째 rendering위치에 고정 l  IOS 4.0이하

-  Web page의 끝 (마지막 element 다음)에 붙임 l  Android 2.3 삼성 단말 오동작

고정

고정

34

CSS position:fixed 처리

¨  JQM에서 position:fixed 처리 방식

l  Browser 엔진에서 지원시 사용

l  Browser 엔진에서 미지원시 처리 방식 -  Scroll 시작시 사라지게하고 종료시 다시 그려줌

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

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

¨  문제점

¤  첫번째 방식 -  scroll시 JavaScript 수행을 중지시키는 경우 화면 update 문제 발생 (삼성

Android 2.3 단말 포함)

-  지속적으로 깜빡 거려서 UX 저하

¤  두번째 방식 -  UX 관점에서 application이라기 보다는 web page의 느낌임

35

Fixed toolbar 지원 대안 1

¨  overflow:scroll을 이용한 우회법

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

l  overflow:scroll을 이용하여 content 영역만을 scroll

¨  문제점

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

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

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

position:fixed

position:fixed

viewport content

position:inline

position:inline

viewport

content overflow:scroll

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

36

JavaScript Scroller: iScroll

¨  iScroll JavaScript scroller: cubiq.org/iscroll-4

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

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

position:absolute

position:absolute

viewport

<div class = wrapper> overflow:hidden position:absolute z-index:1 touchmove event를 wrapper에 binding

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

<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> <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 -->

37

iScroll 기능

¨  iScroll의 기능

l  Pull to refresh

l  Pinch zoom

l  Scrollbar customize

l  Transition mode

-  webkit-transform-timing-function: cubic-bezier 사용 l  Touch 미지원시 mouse fallback

¨  Public method

l  refresh()

l  scrollTo(x, y, time, relative)

l  destroy

38

JQM내에서 iScroll활용

¨  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사용량이 최소한이 되도록 최적화 해야함

39

JQM 사용 Disclaimer

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

l  성능 문제

-  Style 값에 따른 CPU 과다 사용 -  <a> link 포함시 단말별도 반응속도 저하

l  Fixed element 동작 문제

l  Transition 지원 문제

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

40

Audio 기능 제공

¨  Audio관련 상세 requirement

l  cross-platform으로 audio playback 지원

l  LCD off시 연속 재생 지원

l  Background mode 진입시 재생 지원

l  Playlist 지원

¨  <audio> tag 지원

l  Android 2.1 및 2.2 미지원

41

<audio> tag (1/2)

¨  IOS 4.0 >

l  Only user action (e.g. onclick, touchevent) action can play sound: audioElm.play()

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

<body onLoad="document.myMovie.play()"> will not work <input type="button" value="Play" onClick="document.myMovie.play()> will work

42

<audio> tag (2/2)

¨  Audio tag event sequence on real devices

l  Expected occurrence order -  emptied → loadstart → durationchange → loadedmetadata → loadeddata →

canplay → play → playing → canplaythrough → pause → ended

l  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

43

Sound Manager 2

¨  <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(); }); </script>

Not verified for Mobile OS YET!!

44

Playlist 연속 재생

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

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

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

l  기술 이슈 예

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

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

l  Hybrid application으로 변경

-  Hybrid application내의 WebView에서 HTML app loading시 LCD off 모드에서 연속 재생 가능

45

Native-like GUI: Full screen

¨  iOS의 Web App mode로 full screen 만들기

l  Full screen 만들기 -  <meta name=”apple-mobile-web-app-capable” content=”yes>

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

l  시작 화면 -  <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

46

Native-like GUI: Full screen

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

l  Android 및 Web app mode가 아닌 iOS Safari browser 적용

l  Web page의 height를 URL bar height와 window.innerHeight를 더한 값으로 set

¨  Disclaimer

l  Device 별 URL bar 크기 차이

l  URL bar hiding animation 도중 window는 계속적으로 resize 됨

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

https://gist.github.com/1172490

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); };

47

Fast button 제작

¨  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

48

Fast Button 예제: Matteo

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; } };

49

Fast Button: Google Clickbuster

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 = [];

50

Fragmentation handling (1/2)

¨  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

51

Fragmentation handling (2/2)

¨  사용 방법

l  초기화

l  Modernizr.load

초기화 결과 저장 <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">

<!DOCTYPE html> <html> <head>

<meta charset="utf-8"> <title>My Beautiful Sample Page</title> <script src="modernizr-1.5.min.js"></script>

</head>

Modernizr.load({ test: Modernizr.geolocation, yep : 'geo.js', nope: 'geo-polyfill.js' });

52

Web App Platform Architecture

¨  WebKit engine 구조 및 동작

¨  Webkit rendering basics

53

WebKit Open Source Project

¨  Apple, Google 주도의 Open Source Project

¤  Committer/reviewer 분포

n  Web 분야 투자/Leadership 간접 지표

¤  Committer 자격

n  10-20 good patch

n  3명의 reviewer로부터 추천

¤  Reviewer 자격

n  최소 80 good patch

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

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

Reviewer Committer

Apple 39 6

Google 24 32

삼성전자 2

총합 83 60

국내 committer: 4명 삼성전자: 2명 (EFL) Company100: 1명 (Brew) Intel: 1명(Gtk)

54

WebKit 구조

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

¤  Mozilla Firefox, Google Chrome는 Browser가 Open Source

¨  UI, Graphics, network등은 platform 별 별도 구현

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

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

¤  Mac port는 미공개

WebCore JavaScriptCore (SFX, V8)

Platform Port (HW 가속 포함)

WebView (Widget, API)

Browser GUI DB

Plug-in

Network

Native Platform

메모리 관리

Webkit open source 범위

Webkit 기반 Browser

Mac Efl Gtk Qt Android

Mac Efl Gtk Qt Android

WebKit Graphics back-end 구조

WebKit

Native Widget

Cairo/Skia (2D graphics)

OpenGL ES (3D graphics)

HTML, CSS, JavaScript

Native Windowing

55

UI FW

GPU Memory

Browser Process RenderProcess

Skia (2D graphics) Gtk

X server compositor

OpenGL ES / EGL

GPU Process

URL Bar Gtk

Widget

URL bar Webview

Window Buffer

Indicator

Frame Buffer

Platform Port

WebCore

V8

WebCoreSupport WebViewClient

JS FrontEnd

JIT

IPC Channel Resource Dispatcher ResourceLoaderBridge

RenderView

TabContents

RenderViewHost

RenderProcessHost

Glib main loop (Event Queue)

IPC Channel

Resource DispatcherHost

Web Page Gtk

Widget

Plugin Process

IPC Channel

HTTP stack File/DB

NPAPI:: PluginHost

Graphics

Layer Tree

Render Tree

Style

Rules

DOM

Tree

Parser

Loader

GPU Process

Chromium Browser 56

Browser Process

UI FW

GPU Memory

Main Thread

WebViewCoreThread

Skia (2D graphics) Gtk

Surface Manager compositor

OpenGL ES / EGL

Tool Bar

Canvas

Window Buffer

Indicator

Frame Buffer

Platform Port

WebCore

V8

WebCoreSupport WebViewClient

JS FrontEnd

JIT

Message Handler

RenderView

Message Handler (Event Queue)

Webview Graphic

s Layer Tree

Render Tree

Style

Rules

DOM

Tree

Parser

Loader

Canvas

PictureSet

Partially Cached

DOM Node

Android Browser Multi-threaded

57

UI FW

GPU Memory

WebKit

Ecore Main Loop (Event Queue)

Cairo (2D graphics) Evas Ecore

X server compositor

OpenGL ES / EGL

HTTP stack (libsoup)

Evas canvas

URL Bar

Evas Object

URL bar Webview

Pixman (NEON)

Window Buffer

Indicator

Frame Buffer

Platform Port

BackingStore

WebCore

JavaScriptCore (SFX)

WebCoreSupport WebKit API

Page JS FrontEnd

Interpreter or JIT

DOM Data

JS Engine Binder

Graphics Layer Tree

Graphics Layer

Render Tree

Render Object

Render Layer

Style Rule

s

DOM Tree Parser

CSS Parser

HTML Parser

Loader

Resource Load Scheduler

Sub Resource Loader

Main Resource Loader

Node

Network Port Graphics Port

Evas Object Layer Renderer GraphicsContext3D GraphicsContext

Animation Controller

Tizen Browser Multi-threaded

58

DOM과 Render Tree 개괄

http://image.google.com <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>

HTMLDocument RenderView

HTMLHtmlElement 1. Element 생성

2. addChild()

3. rendererIsNeeded? YES

HTMLHeadElement

HTMLTitleElement

HTMLStyleElement

HTMLScriptElement

rendererIsNeeded? NO

5. setRender() RenderBlock 4. RenderBlock 생성

6. addChild()

HTMLBodyElement

HTMLDivElement

HTMLElement(nobr)

HTMLElement(span)

HTMLAnchorElement

Text

HTMLElement(span)

RenderBlock

RenderBlock

RenderInline

RenderInline

RenderInline

RenderText

RenderInline

DOM Tree Render Tree 59

WebKit Rendering Basics(1/4)

¨  내부 Data Structure

<html> <head> </head> <body> <p> hello</p> <div class=“page” > <p>world</p> <div> </body> </html>

.page { position: absolute; width: 100%; height: 100%; -webkit-transform: translate3d(0, 0, 0); }

<head>

<html>

Document

<body>

<p>

hello

<div>

<p>

world

DOM Tree HTML/CSS file

RenderView

RenderText:”Hello”

RenderText: ”World”

Render Tree RenderLayer Tree

RenderRootLayer

RenderLayer1

parsing DOM node attach

조건별 Layer 생성

60

WebKit Rendering Basics(2/4)

¨  내부 Data Structure

RenderView

RenderText:”Hello”

RenderText:”World”

Render Tree RenderLayer Tree

RenderRootLayer

RenderLayer

RenderBoxModelObject:: requiresLayer()

GraphicsLayer Tree (Texture on GPU)

GraphicLayer

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

Hello

World

Z ordering

61

WebKit Rendering Basics(3/4)

¨  Painting 절차: SW path

¤  하나의 graphic buffer를 할당

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

n  Hello를 주어진 buffer에 paint

n  World를 Hello를 paint한 buffer에 칠함

¨  Painting 절차: HW accelerated path: Accelerated Compositing by GPU

¤  CPU graphics buffer와 GraphicsLayer 별 GPU buffer 생성

¤  Layer 별로 painting

¤  모든 결과를 sync하여 compositing

GraphicsContext: Graphic Buffer

Hello

World

GraphicsContext: Graphic Buffer on CPU

Hello

World

GraphicsContext: Graphic Buffer on GPU

Hello

World

Compositing by GPU (Open GL ES)

62

WebKit Rendering Basics(4/4)

¨  HW accelerated path: Accelerated Compositing by GPU

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

¨  장점

¤  속도가 CPU 대비 “order of magnitude”로 빠름

¤  3D transformation은 Accelerated Composting이 enable되어 있을때만 사용 가능

¨  단점

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

¨  iOS 및 Android 4.0이상에서 지원

GraphicsContext: Graphic Buffer on CPU

Hello

GraphicsContext: Graphic Buffer on GPU

Hello

Compositing by GPU (Open GL ES)

63

Silky Smooth Scroll 기술(1/3)

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

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

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

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

viewport

Finger touch

64

Silky Smooth Scroll 기술(2/3)

¨  BackingStore

¤  한번의 scroll로 이동 가능한 영역에 대해서 pre-rendering된 결과를 image로 caching

¤  사용자 Scroll시 pre-rendering된 image의 일부를 cut-n-paste를 하여 viewport로 복사 Reflow/Repaint 제거

Single Image Buffer

65

Silky Smooth Scroll 기술(3/3)

¨  BackingStore

¤  한번의 scroll로 이동 가능한 영역에 대해서 pre-rendering된 결과를 image로 caching

¤  사용자 Scroll시 pre-rendering된 image의 일부를 cut-n-paste를 하여 viewport로 복사 Reflow/Repaint 제거

RenderView

RenderText:”Hello”

RenderText:”World”

RenderRootLayer

RenderLayer GraphicLayer

Z ordering

Viewport보다 큰 영역을 미리 rendering해서 image cache를 해둠 사용자 panning시 이미 rendering된 이미지를 복사해주기만 함

66

¨  Battery Life

¨  CPU utilization

¨  No JS animation, use CSS animation

¨  Repaint/layout를 최소화

¨  Memory bus utilization

¨  Cache miss시 external DRAM read/write발생

¨  image file의 크기 최소화

¨  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 읽기/쓰기

67

Mobile Web App 성능 Factor

End-to-End 성능 최적화 (1/2)

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

68

End-to-End 성능 최적화 (2/2)

From W3C Navigation Timing specification

69

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

¨  [RULE] CSS 2D/3D transforms를 이용한 2D/3D animation 구현은 HW 가속 Accelerated Compositing 기능이 제공 되는 Mobile OS 에서만 사용한다

¨  Mobile OS에서 HW 가속 Accelerated Compositing 지원 현황

¨  JavaScript를 통한 지원 여부 검사 방법 ¤  User agent를 통해 Mobile OS 버전을 알아내서 활용 가능

n  해당 property는 read/write 가능하여 비추천

¤  Modernizr※ JavaScript library 활용 (추천) n  csstransforms, csstransforms3d, csstransitions n  Android 2.1-2.3은 true이나 제대로 동작하지 않음

72

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

var ua = window.navigator.userAgent; Mozilla/5.0 (Linux; U; Android 2.3; en-us) AppleWebKit/999+ (KHTML, like Gecko) Safari/999.9

※ 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  2, 4, 8, 16, 32, …, 1024

¤  PowerVR chip의 PVRTC compressed image 사용시 정사각형 이어야 함: iOS device 계열에서 사용

¤  Max size limit 있음 n  OpenGL ES 1.0 SGX: 1024x1024 n  OpenGL ES 2.0 SGX: 2048x2048

¨  Layer의 크기가 257x257이면 실질적으로는 512x512 크기의 texture를 생성하게 됨 ¤  다수의 layer를 위와 같이 생성시 비효율적인 메모리 사용 증가

※ Graphics Chip Vendor 별로 특성 확인 필요

http://joehewitt.com/2011/10/05/fast-animation-with-ios-webkit

2D/3D Animation 74

¨  [RULE] Animation을 수행하는 영역은 as simple as possible 하게 유지하자

¨  Animation 대상 block이 painting 비용 관점에서 복잡해질수록 Animation시 사용하는 Texture를 초기 생성하는 지연증가로 Animation 개시 지연 발생

¨  Not simple 의미: !(painting cost가 높음) n  CSS filter, shadow, canvas, SVG, 과도한 DOM node 개수, scaled된 image 등

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

2D/3D Animation 75

¨  [RULE] Animation 시나리오상 animation 대상 block은 그것의 visual 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 layer로 mapping 가능

¨  해당 image에 아래 CSS 적용 ¤  -webkit-transform:translate3d(0,0,0) à 별도 layer에 mapping

¨  resource 사용량이 늘어남

79

¨  [RULE] Canvas 2D는 속도가 매우 느리므로 사용을 자제 하자. ¨  기존 HTML/CSS로 표현 불가한 것이 있을 경우 painting 속도를 충분히 분석하고 사용하자 ¤  `12년 Canvas 2D에 대한 HW 가속이 진행중이고 성능 개선이 확인된 후에만 사용하도록 하자

¨  [RULE] Canvas 3D는 현시점 (`12년 1월)에서 Mobile 단말에서 미지원이므로 사용하지 말자

Canvas 2D/3D

성능 개선 Guide – Part 2 80

¨  Parsing/Layout/Rendering

CSS overflow property 81

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

¤  iOS에서는 two finger로 scroll 가능 n  -webkit-overflow-scrolling: touch n  iOS 5 부터 지원: native 수준 성능 제공

¤  Android는 one finger scroll 가능 n  3.0 이후 버전만 scroll 지원 (2.3 이하 미지원)

¨  단점 ¤  일반 화면 scroll에 비해 속도가 느림

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

¤  poor discoverability: 사용자가 scrollable 여부 인지하기 힘듦 n  화면 자산때문에 scroll bar를 지원하지 않음

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

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를 수반

¤  Layout은 serialize된 CPU intensive 작업 ¤  Repaint는 대량의 data copy 연산 발생 야기 à battery 소진

¨  DOM tree가 커지면 layout 비용은 비례하여 증가함 ¤  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에 필요한 containing 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  Z-ordering, fixed positioning n  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를 수행

¨  Repaint 만 발생하는 경우 (layout 미 발생) ¤  Visibility, colors, transforms, backgroud images, transparency

CSS Box Model

Repaint 비용 최소화 87

¨  [RULE] element의 individual style을 반복적으로 변경하지 말고 class 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 aspect 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. The 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 displayed. Thereafter, the user can zoom in and out unless you setuser-scalable to no. Zooming by the user is also limited 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을 반드시 명기하자 ¨  Encoding type 명기법

¤  HTTP header에 명기 (the best way) n  Content-Type: text/xml; charset=ISO-8859-1 n  AJAX의 response header에서도 동일하게 명기

¤  HTML 문서 header에 명기 n  <meta http-equiv="Content-Type" content="text/html; charset=utf-8“>

¨  Encoding auto-detector 단점 ¤  Auto-detector 동작 조건:

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

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

WebKit-r103911\Source\WebCore\platform\text\TextEncodingDector.h

WebKit Text Encoding Source enum EncodingSource { DefaultEncoding, AutoDetectedEncoding, EncodingFromXMLHeader, EncodingFromMetaTag, EncodingFromCSSCharset, EncodingFromHTTPHeader, UserChosenEncoding, EncodingFromParentFrame }

Language encoding 94

¨  [RULE] 가능하면 HTTP response header에 language encoding을 명기하라

¨  Webkit엔진 기반 Browser는 encoding type이 알려질때까지 document를 buffering ¤  HTML parsing과 Script 수행이 바로 되지 않는 지연 발생

http://www.w3.org/TR/REC-html40/charset.html#h-5.2 http://www.kylescholz.com/blog/2010/01/performance_implications_of_charset.html

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

��

Content Size 줄이기 95

¨  [RULE] HTML, JS, CSS는 Minifying 하자 ¤  White space, indent, line break 제거

¨  [RULE] gzip, deflate를 통해 compression을 하자 ¤  Gzip-friendly content 구성 방법론

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

¤  Gzip (deflation) 원리 n  Duplicated string을 찾음 n  두 번째 중복 string 발생시 첫번째 found string으로의 pointer로 대체

n  Pointer는 distance와 length의 pair n  즉, 중복 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  PNG는 Zip compression 압축률 > GIF는 LZW compression 압축률 n  GIMP “indexed”로 생성 (RGB 말고)

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

n  Continuous tone (e.g. gradient)는 lossy compression ¤  Logo나 line art에는 GIF 사용

n  JPG 사용시 이미지 뭉개짐 현상 발생 ¤  BMP와 TIFF는 사용하지 말라

¨  [RULE] 추가적인 image compressor로 좀더 크기를 줄이자 ¤  Image compressor로 추가 무손실 압축

n  JPG: Jpegtran, jpegoptim n  PNG: OptiPNG, PNGOUT

Image Size 줄이기 (2/2) 98

¨  [RULE] 추가적인 image compressor로 좀더 크기를 줄이자 ¤  Image compressor로 추가 무손실 압축

n  JPG: Jpegtran, jpegoptim n  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 rendering이 빠르게 수행된다

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

¤  Page start-up 초기에 필요하지 않는 CSS는 별도의 CSS 파일로 쪽개고 “onload” 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 영역에 box-shadow시 webkit에서 scroll 성능이 느린 defect 미해결 ¤  https://bugs.webkit.org/attachment.cgi?id=80611&action=prettypatch

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"); }

Gradient 104

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

¨  background-image: -webkit-linear-gradient(linear, left top, left bottom, 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-performance

¨  [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 관련 최적화 106

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  Base compiler: minimal한 최적화로 빠르게 코드 생성 n  Runtime profiler: 수행시간 지연 monitoring n  Optimizing compiler: advanced 최적화 기술 적용 및 코드 생성 n  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  element를 삽입하고 synchronous하게 실행함 n  Download하고 실행시까지 parsing은 stop and wait

¤  “async”나 attribute를 갖는 <script> tag를 만나면 n  Download를 개시하고 parsing 계속 n  해당 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 가 되지 않음 ¤  Scheduling, preemption, multiplexing 되지 않음 ¤  Chrome, WebKit2는 multi-process 도입으로 해당 사항 없음

¨  iOS에서의 JavaScript 실행 제약 조건 ¤  수행 시간이 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 사용예

http://www.whatwg.org/specs/web-apps/current-work/multipage/workers.html

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);

Web Worker Thread 사용 (2/2) 114

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

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

¤  접근 불가능 n  DOM access n  Window object n  Document object n  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에 의해 등록된 Callback을 호출 ¤  Mobile OS 별로 화면 갱신 방식의 차이가 있음

n  vsync를 사용하는 system은 실제 LCD screen buffer로의 복사 frequency가 해당값에 제약 받음

n  vsync 60 fps system은 JavaScript 수준 animation에서 그것을 초과하는 frame rate을 구현할수 없음

n  e.g.) 60 fps시스템 à 60/sec로 호출 best effort, not guaranteed

¨  지원 시스템 ¤  Safari, Chrome, Firefox ¤  Mobile에서는 도입 예정

requestAnimationFrame (2/2) 117

¨  사용시 장점 ¤  동시에 발생하는 각종 animation을 browser 수준에서 최적화 할수 있음

n  JS animation과 CSS transition을 synchronize 가능함 n  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의 loading은 미루자

¨  Script 수행 철칙: 어길 시 수행 결과의 correctness를 깨트림 ¤  “Script Execute In Order” ¤  “Script Execute after fully loading all stylesheets”

¨  JavaScript loading 방식: <script src =“file.js”> 및 inline JavaScript는 HTML parsing, page rendering을 block 시킴 ¤  HTML parsing 도중 inline 또는 external JavaScript를 만나면

n  Inline JavaScript는 parsing후 호출이 되었으면 실행 n  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를 최소화 하는 것이 전체 page loading 성능 개선이 필수적임 ¤  Page startup 동안 꼭 필요한 JavaScript를 제외하고, page startup 이후로 def

erring

¨  Deferring 방법 ¤  “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 사용 ¤  <script src="script.js" type="text/javascript" defer="defer"></script>

¨  async attribute 사용 ¤  <script defer src="siteScript.js" onload="myInit()"></script>

¨  async 와 defer의 공통점 ¤  Parser를 멈추지 않고 해당 script download를 즉시 시작함 ¤  Optional onload handler에서 initialization 수행

¨  async 와 defer의 차이점 ¤  async는 download가 끝나는 시점과 window load event 전에 실행됨 ¤  defer는 async와 동일하나 defer된 순서를 지켜서 수행하고 parsing이 끝나는 시점에서 DOM

ContentLoaded event 발생전까지 수행됨 n  DOMContentLoaded

n  해당 page의 document parsing이 완료되고, 즉 DOM tree 가 완성시 fire n  Referenced stylesheet, image, subframe 적재는 안끝날수도 있음

n  Window load n  Subresource까지의 loading이 끝났을때 발생

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

http://davidwalsh.name/html5-async

JavaScript loading 최적화 (4/6) 122

¨  Programmer driven 최적화 ¤  JavaScript의 module 화 및 lazy loading

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

¨  Lazy loading 적용 사례 ¤  Script as DOM

¤  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

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

JavaScript loading 최적화 (5/6) 123

¨  WebKit이 HTMLDocumentParser의 동작 ¤  external script의 download, 실행 완료까지 HTMLDocumentParser가 block

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

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

¨  WebKit PreloadScanner ¤  HTMLDocumentParser가 block 되는 동안 미리 download 가능한 subresour

ce (CSS, JS)가 있는지를 speculatively하게 scan 하여 download 개시 n  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  iOS UIEvent n  http://developer.apple.com/library/safari/#documentation/UserExperience/Refere

nce/TouchEventClassReference/TouchEvent/TouchEvent.html n  iOS Safari JavaScript Object

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

n  현재 널리 채택되어 사용되고 있음

iOS User Interaction Guide 130

¨  Browser vendor 및 Platform 별로 호환성이 차이 분석 ¤  iOS상 click 동작: clickable element에서의 click시 아래의 순서로 발생

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

¤  iOS상 scroll 동작 n  Pan 동작 완료 시점에 1회 발생

iOS 지원 Event 현황 131

Event Generated Conditional Available abort Yes No iOS 1.0 and later. blur Yes No iOS 1.0 and later. change Yes No iOS 1.0 and later. click Yes Yes iOS 1.0 and later. copy No N/A cut No N/A drag No N/A drop No N/A focus Yes No iOS 1.0 and later. gesturestart Yes N/A iOS 2.0 and later. gesturechange Yes N/A iOS 2.0 and later. gestureend Yes N/A iOS 2.0 and later. load Yes No iOS 1.0 and later. mousemove Yes Yes iOS 1.0 and later. mousedown Yes Yes iOS 1.0 and later. mouseup Yes Yes iOS 1.0 and later. mouseover Yes Yes iOS 1.0 and later. mouseout Yes Yes iOS 1.0 and later. orientationchange Yes N/A iOS 1.1.1 and later. pagehide Yes No iOS 4.0 and later. pageshow Yes No iOS 4.0 and later. paste No N/A reset Yes No iOS 1.0 and later. selection No N/A submit Yes No iOS 1.0 and later. touchcancel Yes N/A iOS 2.0 and later. touchend Yes N/A iOS 2.0 and later. touchmove Yes N/A iOS 2.0 and later. touchstart Yes N/A iOS 2.0 and later. unload Yes No 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의 panning은 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에서와 같이 빠른 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

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 ¤  <div>, <ol>, <ul>, <table>, <img> element를 찾고 해당 element가 block일 경우 content를 화면 크기에 fitting 시키고 중앙으로 이동

¨  Android상 double tap for zooming ¤  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 request 발생 최소화 하자

¨  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에 의한 image 왜곡이 심각하게 발생할 수 있으니 최대 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 분리하고 실행하라

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

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

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

¨  즉, page load 전과 후에 필요한 큰 file 두개로 나누어서 관리 하도록 하자

Combine external CSS files 144

¨  [RULE] CSS file 최적화 방식을 따르라 ¤  화면 rendering시 필요한 CSS와 그외 2개로 나누어라 ¤  잘 방문하지 않는 component의 CSS는 별도의 파일로 분리하여 제공 ¤  Cache가 되지 않는 CSS는 inline을 하라

n  Layout 변경으로 layout cost가 증가할수 있음 ¤  CSS @import 를 사용하지 말아라

DNS look-up time 최소화 145

¨  [RULE] hostname 대신 URL path를 사용 하라 ¤  E.g) developer.example.comà example.com/developer ¤  Single domain에서 1) TCP connection 재활용률 높아짐, 2) DNS lookup 없이 single session 사용

¨  [RULE] main document에 load된 JavaScript 파일과 동일한 hostname으로 JavaScript가 적재되도록 구성하자 ¤  “initial rendering”을 위해서 critical path를 minimize 해야함 ¤  JavaScript는 다른 resource download를 blocking을 시키는데, DNS lookup

time까지 들어가면 impact가 큼 ¤  동일한 JS file이 cross page에 사용되면 URL을 동일하게 해야 cache hit율을 높임

http://code.google.com/speed/page-speed/docs/rtt.html

Asynchronous resource 적재 146

¨  [RULE] script DOM element를 사용하자 ¨  Initial view를 만드는데 필요 없는 JavaScript는 asynchronous하게 l

oading해서 DOM에 붙여라 ¨  Script DOM element 사용예

¨  http://stevesouders.com/efws/couple-script-dom.php

var domscript = document.createElement('script'); domscript.src = "menu.js"; document.getElementsByTagName('head')[0].appendChild(domscript);

Compression 사용 147

¨  [RULE] gzip, deflate를 사용해서 data size를 줄이자 ¨  최소 150-1000bytes 이상일 경우 압축 효과가 있다.

¤  150bytes 보다 작을 경우 오히려 압축후 overhead 커진다

¨  Local에 저장된 resource 일 경우도 유효한지 파악해보자 ¨  [RULE] compression-efficient하게 web page content를 준비하자

¤  Ensure consistency in HTML, CSS ¤  Minify JavaScript and CSS

¨  [RULE] image 나 binary 파일은 gzip을 사용하지 말아라

http://code.google.com/speed/page-speed/docs/payload.html http://code.google.com/speed/articles/use-compression.html

Resource download 148

¨  [RULE] resource download를 hostname간 병렬로 진행하도록 하자 ¨  Google map에서 적용 사례

Request size 최소화 149

¨  [RULE] server-side storage를 사용하고 client-side cookie에는 ID만을 저장하라

¨  [RULE] 중복되거나, 사용하지 않는 cookie field를 제거하라 ¨  이상적으로 HTTP request는 하나의 packet으로 구성되어야 함

¤  1500bytes이내로 구성

¨  Cookie는 per-domain으로 자동으로 붙어서 감 ¤  Cookie가 필요없는 content가 주를 이루면 domain 분리 검토

HTTP Pipelining을 사용하자 150

¨  [RULE] HTTP 1.1 pipelining을 사용하라 ¨  Opera, Android, iOS 5부터 지원 ¨  “Connection: Keep-Alive”

Prerendering 151

¨  사용자가 loading 할 것으로 예상되는 link된 HTML 문서를 background에서 load후 rendering을 수행하는 방식

¨  Chrome-only 기능

¨  자원 (CPU, network, memory)를 speculative 하게 추가로 사용하므로 신중해야함 ¤  Network information API를 통해 WiFi등 고속일 경우에 한해서 적용

<link rel="prerender" href="http://example.com/">

function setupApp(){ // create a custom object if navigator.connection isn't available var connection = navigator.connection || {'type':'0'}; if (connection.type == 2 || connection.type == 1) { //wifi/ethernet //Coffee Wifi latency: ~75ms-200ms //Home Wifi latency: ~25-35ms //Coffee Wifi DL speed: ~550kbps-650kbps //Home Wifi DL speed: ~1000kbps-2000kbps fetchAndCache(true); } else if (connection.type == 3) { //edge //ATT Edge latency: ~400-600ms //ATT Edge DL speed: ~2-10kbps fetchAndCache(false);

} else if (connection.type == 2) { //3g //ATT 3G latency: ~400ms //Verizon 3G latency: ~150-250ms //ATT 3G DL speed: ~60-100kbps //Verizon 3G DL speed: ~20-70kbps fetchAndCache(false); } else { //unknown fetchAndCache(true); } }

BW에 따른 최적화 152

¨  [RULE] connection 종류에 따른 content 제공 차등 ¨  navigator.connection (Android only) ¨  높은 bandwidth일 경우 더 높은 해상도/quality를 제공

{ type: 4, UNKNOWN: 0, ETHERNET: 1, WIFI: 2, CELL_2G: 3, CELL_3G: 4 }

(function(){ // sandbox our code if(!navigator.connection) navigator.connection = {type:0, UNKNOWN: 0}; // polyfill var connection = navigator.connection; if(connection.type === connection.WIFI || connection.type === connection.ETHERNET) { // high bandwidth } else { // normal bandwidth } })();

FE 성능 개선 Guide – Part 5 153

¨  jQuery

jQuery selector 내부 동작 154

¨  jQuery는 위 문장을 아래와 같이 자동으로 변환 ¤  한편의 poetry와 같이 복잡함을 합축한다

var tables = document.getElementsByTagName(‘table’); for (var t = 0; t < tables.length; t++) { var rows = tables[t].getElementsByTagName("tr"); for (var i = 1; i < rows.length; i += 2) { if (!/(^|s)odd(s|$)/.test(rows[i].className)) { rows[i].className += ‘odd’; } } };

jQuery(‘table tr:nth-child(odd)’).addClass(‘odd’)

$(‘table tr:nth-child(odd)’).addClass(‘odd’)

Selector 동작 특성을 알고 써라 155

¨  [RULE] browser 별 selector를 동작 특성을 이해하고 사용하라

http://www.slideshare.net/AddyOsmani/jquery-proven-performance-tips-tricks

Selector 종류 예제 동작 속

도 상세 분석

ID 및 Element $(`#Element, form, input’) 빠름 Native DOM 연산으로 구현됨 getElementsByID, getElementsByTag

Class $(`.element’) 일부 browser느림

IE5-8에서 Native DOM 연산 미구현 FF3+, Safari 4+, Chrome 4+, Opera 10.10+에서는 Native DOM 연산 구현 * Mobile Browser에서 테스트 필요

Pseudo 및 Attribute

$(`:visible, :hidden’); $(`[attribute=value]’);

매우 느림 Native DOM 연산 미구현 W3C Selector API인 querySelector, querySelctorAll을 사용하도록 구현하면 빨라짐

http://www.vanseodesign.com/css/css-selector-performance/

http://api.jquery.com/category/selectors/

Selector 동작 속도 비교 156

¨  http://jsperf.com/dh-jquery-1-4-vs-1-6/13

Parent/Child 구조 이해하기 157

¨  $(‘.child’, $parent).show(); //context ¤  5~10% 느림: $parent.find(‘.child’).show();로 translate하는 overhead

¨  $parent.find(‘.child’).show(); //find() ¤  가장 빠름

n  Parent selector가 already cached되어 DOM으로부터 refetch 필요없음 n  Without caching, ~16% slower n  getElementById, getElementByName, getElementsByTagName을 바로 사용 n  .find()는 recursive top-down search를 모든 child 및 sub-elements에 수행

¨  $parent.children(‘.child’).show(); //immediate children ¤  ~50% 느림

¨  $(‘#parent > .child’).show(); //child combinator selector ¤  ~70% 느림

¨  $(‘#parent .child’).show(); //class selector ¤  ~77% 느림

¨  $('.child', $('#parent')).show(); //created context ¤  ~23% 느림

http://jsperf.com/jquery-selectors-context/2

jQuery는 꼭 필요한 경우만 사용 158

¨  jQuery’s ID selector only gets to document.getElementById after parsing the selector and creating a jQuery object

$('a').bind(‘click’, function(){ console.log('You clicked: ' + $(this).attr('id')); });

DOM 접근 효율화 159

¨  [RULE] 불필요한 jQuery selector를 사용하지 말고 DOM 접근을 직접하라

¨  this.id와 $(this).attr(‘id’)는 모두 동일한 값을 return ¨  this.getAttribute(‘id’)는 $(this).attr(‘id’)에 동일함

http://jsperf.com/el-attr-id-vs-el-id/2

DOM 접근 효율화 160

¨  [RULE] DOM 접근 결과는 Caching하여 재사용하라 ¨  Uncached selectors 는 cached selectors에 비해 아래 test에서 62

%까지 성능이 느림 ¤  http://jsperf.com/ns-jq-cached

Cache 및 미Cache 비교 var parents = $(‘.parents’), //caching children = $(‘.parents’).find(‘.child’), //bad kids = parents.find(‘.child’); //good

foo를 통한 Caching 예제 var foo = $(‘.item’).bind('click', function({ foo.not(this).addClass(‘bar’) .removeClass(‘foobar’) .fadeOut(500); }); foo가 garbage collect가 되지 않고 계속 사용됨

jQuery Chaining (1/2) 161

¨  var parents = $(‘.parents’).doSomething().doSomethingElse(); ¨  Selector 연산의 결과로 jQuery object가 return 되면 해당 object에 대한 method를 계속적으로 호출가능

¨  //Without chaining ¤  $(‘#notification’).fadeIn(‘slow’); ¤  $(‘#notification’).addClass(‘.activeNotification’); ¤  $(‘#notification’).css(‘marginLeft’, ‘50px’);

¨  //With chaining ¤  $(‘#notification’).fadeIn(‘slow’).addClass(‘.activeNotification’).css(‘margin

Left’, ‘50px’);

jQuery Chaining (2/2) 162

¨  [RULE] chaining을 사용하면 return되는 jQuery object를 caching하여 재사용함으로써 성능이 향상됨

¨  http://jsperf.com/jquery-chaining

Event Delegation 163

¨  .bind(), live(), delgate() 속성을 알고 쓰자 ¨  .live() vs .delegate() vs. delegate from body variations

¤  http://jsperf.com/jquery-delegate-vs-live-table-test/2

¨  bind() vs .click() vs. live() vs. delegate() ¤  http://jsperf.com/bind-vs-click/12

¨  • .live() vs .live() context vs .delegate() vs. delegating to document.body ¤  http://jsperf.com/jquery-live-vsjquery-delegate/15

DOM은 접근 효율화 164

¨  [RULE] .append(), .insertBefore(), .insertAfter()는 costly 연산이므로 최소한 사용하도록 하자

¨  .append() 사용 tip ¤  HTML building은 in-memory에서 수행하고 한번의 .append로 붙이자 ¤  .append는 cache가 되어 있지 않을 경우 90%까지 느리고 되어 있어도 20% 가량까지 느리다

¨  .detach를 사용하자 ¤  Node에 heavy interaction할 경우 detach후 연산이 완료되면 re-insert하자 ¤  Up to 60%까지 빠름 $(‘p’).click(function(){

$(this).toggleClass(‘off’); }); var p; $(‘button’).click(function(){ if ( p ) { /*..additional modification*/ p.appendTo(‘body’); p = null; } else { p = $(‘p’).detach(); } });

DOM은 접근 효율화 165

¨  일반적인 jQuery .data 사용법 ¤  $(‘#elem’).data( key , value );

¨  빠른 방식 사용법 ¤  $.data(‘#elem’, key , value);

¨  jQuery object를 생성과 data-parsing overhead를 최소화하여 성능 향상함

¨  $.data 방식이 빠르나 selector로 전달되지 않고 오로지, node로만 전달됨 ¤  $.data(elem, key, value) works where elem is already defined as an ele

ment.

jQuery object의 생성을 최소화 166

¨  jQuery의 method중 jQuery Object를 생성하는 것은 사용을 최소화 한다

¨  $(‘a’).map(function(){ return $(this).text();}); ¨  Developers commonly create new jQuery objects on iterations

such as the above just to access some text ¨  Using a lower-level method like $.method() rather than $.fn.me

thod() can help improveperformance with this

Use efficient CSS selectors 167

¨  [RULE] Avoiding inefficient key selectors that match large number of elements ¤  avoid a universal key selector ¤  Make your rules as specific as possible ¤  Remove redundant qualifiers ¤  Avoid using descendant selectors especially those that specify redunda

nt ancestors ¤  Use class selectors instead of descendant selectors ¤  Avoid :hover pseudo-selector for non-link elements for IE

¨  Style system이 match를 빨리 시키거나, 없으면 빨리 끝날수 있도록 하는 것이 중요 ¤  어떻게 되는지 webkit 엔진에서 분석 해보자 ¤  jQuery에도 적용해보자

http://www.w3.org/TR/CSS2/selector.html#descendant-selectors

Inefficient selectors 예제 168

¨  Inefficient한 rule들의 예제 ¤  Rules with descendant selectors

¨  Rules with child or adjacent selectors

Rules with the universal selector as the key body * {...}

.hide-scrollbars * {...} Rules with a tag selector as the key ul li a {...}

#footer h3 {...} * html #atticPromo ul li a {...]

descendant selectors are inefficient because, for each element that matches the key, the browser must also traverse up the DOM tree, evaluating every ancestor element until it finds a match or reaches the root element. The less specific the key, the greater the number of nodes that need to be evaluated.

Rules with the universal selector as the key body > * {...}

.hide-scrollbars > * {...} Rules with a tag selector as the key ul > li > a {...}

#footer > h3 {...} Child and adjacent selectors are inefficient because, for each matching element, the browser has to evaluate another node. It becomes doubly expensive for each child selector in the rule. Again, the less specific the key, the greater the number of nodes that need to be evaluated. However, while inefficient, they are still preferable to descendant selectors in terms of performance.

Inefficient selectors 예제 169

¨  Rules with overly qualified selectors

¨  Rules that apply :hover pseudo-selector to non-link elements

Rules with overly qualified selectors For example:ul#top_blue_nav {...}

form#UserLogin {...} ID selectors are unique by definition. Including tag or class qualifiers just adds redundant

information that needs to be evaluated needlessly.

Rules that apply the :hover pseudo-selector to non-link elements For example:h3:hover {...}

.foo:hover {...} #foo:hover {...} div.faa :hover {...}

The :hover pseudo-selector on non-anchor elements is known to make IE7 and IE8 slow in some cases*. When a strict doctype is not used, IE7 and IE8 will ignore :hover on any element other than anchors. When a strict doctype is used, :hover on non-anchors may cause performance degradation.

End-To-End 성능 profiling

¨  Profiling tool 및 특성

¨  PageSpeed 기반 실적용 사례

170

Google Page Speed 171

¨  동작 ¤  Google에서 작성한 Web 성능 best practices들을 기준으로 작성된 site에 적용하여

100점 만점으로 평가하여 점수를 제공 ¤  Best Practice에 위배되는 경우에는 해당 사항을 최적화 하기 위한 guide와 함께 적용한 결과물들까지 제공함

¨  Best practice 기술 상세 정보 ¤  http://code.google.com/intl/ko-KR/speed/page-speed/docs/rules_intro.html

¨  Online 형태로 제공되는 서비스 ¤  http://code.google.com/intl/ko-KR/speed/pss/

¨  Google Chrome browser 통한 서비스 (Chrome extension) ¤  http://code.google.com/intl/ko-KR/speed/page-speed/docs/using_chrome.ht

ml ¨  사용성

¤  Mobile 또는 desktop 용 Web site 제작시 사용 가능 ¤  Local에 설치되는 web app은 다수 적용 가능

Google Speed Tracer 172

¨  동작 ¤  Browser에서 발생하는 각종 연산의 지연을 lo

w level에서 수집하여 timeline으로 도시해주는 tool

¤  Lowe level event n  DOM Event, Layout, Recalculate styles, P

aint, Parst HTML, Timer install, XHR, Network, JavaScript callback

¨  Project site ¤  http://code.google.com/intl/ko-KR/webto

olkit/speedtracer/ ¨  사용성

¤  주어진 app의 실행동안 발생하는 browser 내부 동작 상세 정보를 파악 가능함

¤  Web site/web app 모두 적용 가능

Yahoo YSlow 173

¨  동작 ¤  Yahoo에서 제시한 34가지 Web 성능 Best Practice Rule를 주어진 web site에

적용하여 분석후 Grade로 최적화 방안과 제시 ¤  Rule matrix 상세

n  http://developer.yahoo.com/yslow/matrix/

¨  Project site ¤  http://developer.yahoo.com/yslow/

¨  특징 ¤  iPhone에서 bookmarklet 버전을 제공 ¤  http://developer.yahoo.com/yslow/mobile/

Closure Compiler (1/3) 174

¨  동작 ¤  JavaScript의 크기를 줄여서 download 속도를 개선 ¤  JavaScript 코드 분석후 dead code 제거등의 코드 최적화를 수행하는 JavaScri

pt-to-JavaScript compile을 통해 수행속도를 빠른 JavaScript 코드를 생성해 줌

¨  Project site ¤  http://code.google.com/closure/compiler/

¨  Online Closure compiler ¤  http://closure-compiler.appspot.com/home

Closure Compiler (2/3) 175

¨  Closure compiler compilation level ¤  Whitespace only

n  Comment, white space, line break만 제거한 버전으로 original source 코드와 identical ¤  Simple optimization

n  Whiespace only 적용 n  Expression과 function 내에서 local 변수와 function parameter renaming: local에만 한정함으로 다른 library와의 interface는 문제 없음

n  Syntactically valid JavaScript를 preserve ¤  Advanced optimization

n  Simple optimization 적용 n  More aggressive renaming: global variable, function, properties를 포함 n  Dead code removal: unreachable code 제거 (open source library의 일부만 사용시 유용한 기능)

n  Global inlining n  Interoperability 가 깨질수 있음: function 이름 변경등으로 interface mismatch 발생 가능

à 적용전 guide를 따라야함 (http://code.google.com/closure/compiler/docs/api-tutorial3.html)

Closure Compiler (3/3) 176

¨  Simple과 advanced option 적용 결과 예 ¤  Advanced일 경우 높은 앞축률과 코드 분석 수준 정도가 높음

JSLint 177

¨  동작: http://www.jslint.com/ ¤  JavaScript에서 code quality를 분석하는 tool ¤  JavaScript 대부 Yahoo의 Douglas Crockford가 유지보수

¨  사용법 ¤  www.jslint.com에서 online 서비스로 제공

JS Minifier 178

¨  YUI Compressor ¤  Space 및 indentation을 제거하여 파일 크기를 줄여주는 java로 작성된 tool ¤  http://developer.yahoo.com/yui/compressor/

¨  JSMin ¤  Space 및 indentation을 제거하여 파일 크기를 줄여주는 C로 작성된 tool ¤  http://crockford.com/javascript/jsmin

¨  JavaScript Compressor ¤  Online 서비스로 제공 ¤  http://minifyjavascript.com/

DOM Monster (1/2) 179

¨  동작 ¤  DOM 정보를 분석하여 수치로 제공 ¤  http://mir.aculo.us/dom-monster/ ¤  Bookmarklet 형태로 제공

n  Bookmarklet은 bookmark에 등록이 되는 JavaScript로 click시 등록된 JavaScript가 실행됨

¨  분석 정보 ¤  해당 page의 DOM 개수 및 불필요한 element 정보등을 제공 ¤  DOM 관련된 최적화 정보 추가 제공

DOM Monster (2/2) 180

¨  11번가 적용 결과

PageResource 181

¨  Steve Shoulder의 Performance 측정 및 최적화 guide tool ¤  http://stevesouders.com/mobileperf/pageresources.php ¤  Bookmarlet 형태로 제공되는 tool

결과 도출

HTTP Archive (1/2) 182

¨  동작 ¤  Web page resource의 statics을 분석 하여 display ¤  Waterfall 형태로 web page loading 시간을 측정해서 display ¤  Online 서비스 형태로 무려 제공

n  http://httparchive.org/websites.php ¤  11번가 적용 결과

n  http://www.httparchive.org/viewsite.php?pageid=732802

HTTP Archive (2/2) 183

Browserscope 184

¨  동작 ¤  Online에서 Web browser 성능 profiling ¤  http://www.browserscope.org/

¨  Profiling 분야 ¤  Security, rich text, selectors API, network, Acid3

¨  사용 ¤  Web app/site 분석에는 적합하지 않고 target browser의 성능 분석용으로 적합

Yahoo Smush 185

¨  동작 ¤  Lossless 압축 및 불필요한 byte를 제거하여 크기 최적화를 해주는 image tool로

online으로 서비스됨 ¤  http://smush.it/

CSS Sprite Generator 186

¨  동작 ¤  HTTP request를 개수를 줄이기 위하여 여러장의 image를 아래의 그림에서와 같이 한장으로 묶는 tool

¤  http://spritegen.website-performance.org/ ¤  http://spriteme.org/

WebP 187

¨  동작 ¤  Google 제안한 새로운 image format으로 25-34% 사이즈를 줄임

¨  Project site ¤  http://code.google.com/intl/ko-KR/speed/webp/index.html

¨  제약 사항 ¤  Chrome, ICS, plugin(Opera, IE)에서만 지원

CSSLint 188

¨  동작 ¤  CSS error를 찾아주는 online tool ¤  http://csslint.net/

¨  사용 ¤  Web site/app 개발시 사용 가능

ControlJS 189

¨  동작 ¤  JavaScript module loading을 빠르게 해주는 JavaScript ¤  http://controljs.org/

¨  기능 ¤  Script를 asynchronously download ¤  Inline/external script 처리 ¤  Page rendering 시점까지 script 실행 defer

Tool 적용 상세 예 190

¨  Page Speed ¤  11st 및 멜론

Page Speed: jQuery mobile 191

¨  http://jquerymobile.com/demos/1.0/docs/lists/lists-formatting.html

22점

압축 사용 192

¨  Web server를 Content-Encoding을 모든 compressible resource (HTML, CSS, JavaScript)에 gzip 적용

¨  150-100bytes 이상일 경우 compression/decompression overhead를 상쇄 가능

JavaScript/CSS minification 193

¨  Space, indent, line break등을 제거 ¤  Closure Compiler, JSMin, YUI Compressor 사용

¨  Page speed를 적용하면 하기 directory에 Closure Compiler와 JSMin을 적용한 결과를 저장함 ¤  Linux:/tmp/page-speed-[css | javascript | images]/ ¤  Windows: C:\Documents and Settings\username\Local Settings\Temp\page-spe

ed-[css | javascript | images]\ ¤  Mac OS X: /Users/username/Library/Caches/page-speed-[css | javascript | imag

es]/

Browser Caching 활용 194

¨  캐시 가능한 resource 갱신 기간 증가 시키기

Keep-Alive 사용 195

Character Set 지정 196

Vary: Accept-Encoding 헤더지정 197

¨  Proxy에서 cache 성능 개선

불필요한 Reflow 없애기 198

¨  Layout (reflow)를 최소로 하는 방식 제공 필요 ¤  Web app은 incremental rendering 보다는 all-ready-shot rendering이 더 적합

Page Speed: Sencha Touch 199

¨  http://dev.sencha.com/deploy/touch/examples/kitchensink/

JavaScript 파싱 지연 200

¨  해당 page에서 사용하지 않는 다수의 JavaScript 파일의 다운으로 인한 rendering 지연 발생

일관된 URL에서 리소스 제공 201

¨  두개는 동일한 파일이므로 동일한 URL로 변경

캐시 유효성 검사기 지정 202

요청 직렬화 줄이기 203

불필요한 reflow 제거 204

Page Speed: Mobile 11번가 205

이미지 최적화 206

¨  Image compressor로 추가 무손실 압축 ¤  jpeg: Jpegtran, jpegoptim ¤  PNG: OptiPNG, PNGOUT

조정된 이미지 제공 207

¨  Image가 실제 사용되는 크기로 조정하자

이미지 크기 지정 208

¨  Image의 크기를 미리 지정하면 layout 회수를 감소 시켜 rendering 성능을 개선 가능

불필요한 Reflow 없애기 209

¨  JavaScript가 이야기 시키는 reflow를 검토해보고 제거하자

Reference (Article) ¨  Google Page Speed 문서 site

¤  http://code.google.com/speed/page-speed/docs/overview.html

¨  Google Web 관련 Tool 모음

¤  http://code.google.com/intl/ko-KR/speed/tools.html

¨  Gmail latency 개선 사례

¤  `://googlecode.blogspot.com/2009/09/gmail-for-mobile-html5-series-reducing.html

¨  Mobile UI 개선 Tip(by Estelle Weyl)

¤  http://calendar.perfplanet.com/2011/mobile-ui-performance-considerations/

¨  Page Speed 적용 Web Site 분석 Online Tool (by AOL, open sourced)

¤  http://www.webpagetest.org/

¨  QuerySelect와 QuerySelectAll의 WebKit Article

¤  http://www.webkit.org/blog/156/queryselector-and-queryselectorall/

210

Reference (Article) ¨  www.jquery.com

¨  www.jquerymobile.com

¨  How Browsers Work : Behind the Scenes of Modern Web Browsers (Tali Garsiel)

¨  http://www.html5rocks.com/en/tutorials/internals/howbrowserswork/

¨  http://www.youtube.com/watch?v=dndeRnzkJDU

¨  http://www.webkit.org/coding/technical-articles.html

¨  http://www.slideshare.net/joone/hardware-acceleration-in-webkit?ref=http://opensoftware.kr/

¨  http://www.html5rocks.com/en/mobile/optimization-and-performance/

¨  Google page speed: https://developers.google.com/speed/pagespeed/ (tool 및 tool이 적용하는 기술에 대한 article있음)

¨  jQuery 성능 최적화 tip: http://www.slideshare.net/AddyOsmani/jquery-performance-tips-and-tricks-2011

¨  http://www.schillmania.com/projects/soundmanager2/

¨  http://www.html5rocks.com/en/tutorials/detection/index.html

¨  www.modernizr.com

¨  HTML5 polyfills: https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-Browser-Polyfillshttp://www.webkit.org/blog/156/queryselector-and-queryselectorall/

211