2. Contents
Mobile Web Application 정의
●
Server-hosted, Hybrid
Mobile Web Application SW Architecture 구성
●
UI/UX 개발: jQuery, jQuery Mobile
●
Audio 기능 개발: Sound Manager2
●
Fragmentation handling: Modernizr
●
Common utilities: touch library, URL bar control
Mobile Web Application 구동 환경의 이해
●
Mobile browser engine architecture
Mobile Web Application End-To-End 성능 최적화 방법론
●
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 기술 분야
SW 개발자 HTML5/Web App 개발자 Web designer
(Programming) (Programming) (Publishing)
ss
Java/C++/Objective C HTML5 HTML4 Flash
Native
Algorithm CSS3.0 CSS2.1
API
Compiling HW
최적화 JavaScript JavaScript
(system/module/logic) (DHTML) DOM
ARM GPU
Browser
6. Mobile Web Application 분류
6
동작 및 배포 방식에 따른 구분
●
Server hosted
●
Hybrid
강좌 목표: Server Hosted의 Pure Web App 개발 기술 Practice
Remote Server Web Data Web Data Web Data
HTML5 App
On target device Native
HTML5 App
Part
Container/Binder
Native Web App Browser
(PhoneGap, AppMobi)
WebView WebView WebView
Binder
(WebKit) (WebKit) (WebKit)
Android/iOS Android/iOS Android/iOS
7. 시장 사례 분석
7
Melon 사례
●
Server hosted: m.melon.com, t.melon.com
●
Hybrid: iOS 및 Android app
11번가 사례
●
Server hosted: m.11st.co.kr
●
Hybrid: iOS 및 Android app
8. Web App 개발 요구사항
8
본 강좌에서 가정하는 Mobile Web app의 상위 수준 요구사항으로 이를
만족하는 audio application 개발 상품화하는 시나리오를 설정
●
단말에서 구동되는 Mobile browser내에서 동작 해야함
●
Native 수준의 뒤 떨어지지 않는 GUI/UX 를 제공하여야 함
●
Audio playback을 제공해야함
●
Cross-platform 지원 해야함
– Android 2.1/2.2/2.3/3.0/4.0 및 Chrome for Android
– IOS 3.0/4.0/5.0
– Blackberry OS 6.0/7.0
●
UX 저하가 없는 수준의 성능을 제공 해야함
●
작성한 코드는 다른 Application 개발에도 재활용이 가능해야함
10. Web App SW Architecture
Open source기반 Web application SW 구조
●
Open source 활용시 다양한 configuration이 가능하고 하나의 예임
Open source 선택시 필수 고려사항
●
Community가 활성화정도, 안정 버전 release 주기
●
License 종류, 회사 편향도
HTML5 audio application Audio Fragmentation
UI Framework
FW Handling
jQuery Mobile + plug-in URL
Fast Sound
iScroll Bar Modernizr
Button Manager2
jQuery + plug-in Handler
DOM (Document Object Model)
Browser
WebView (WebKit)
Android/iOS/Blackberry OS/Kindle Fire
Application processor, GPU
11. UI 상세 명세서 일부
아래의 3분류의 화면 Template 제공하고 화면간 이동 및 이동시 trans-
ition effect를 지원 해야함
노래 목록은 위 아래 scroll이 가능해야하고 이때 상단 및 하단 메뉴는 화
면에 고정 되어있어야 함
고정
화면 전환 화면 전환
및 효과 및 효과
고정
12. jQuery
12
“simplifies HTML document traversing, event handling, an-
imating, and Ajax interactions for rapid web development”
from jquery.com
jQuery 표현력 및 생산성 예
$(‘table tr:nth-child(odd)’).addClass(‘odd’)
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 overhead VS 생산성/유지보수/확장서
●
단말에서 DOM 직접 접근 대비 7배 정도 느림
13. 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/
14. JQM Widget
지원하는 widgets
●
Pages, dialogs, toolbars, listview, button, form element,
accordion, collapsibles
17. Multi page template
<body>
<!-- Start of first page -->
<div data-role="page" id="foo">
<div data-role="header"> Page foo
<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 -->
slide pop
<div data-role="footer">
<h4>Page Footer</h4>
</div><!-- /footer -->
</div><!-- /page -->
<!-- Start of second page -->
<div data-role="page" id="bar"> 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" data-transition="slide">Back to foo</a></p>
</div><!-- /content -->
<div data-role="footer">
<h4>Page Footer</h4>
</div><!-- /footer -->
</div><!-- /page -->
</body>
18. Web based WISWYG Editor
Codiqa
●
GUI editor
ThemeRoller Mobile
●
Theme editor
ThemeRoller Mobile
Codiqa (charged)
19. UI 명세서 중간 점검
JQM widget set 구성으로 구현 가능
●
Page 3개, Listview, header/footer with position fixed
고정
화면 전환 화면 전환
및 효과 및 효과
고정
20. HTML5 Data- attribute
data-* attribute 추가
●
Custom attribute 정의하여 사용 가능
<li id="appDeveloperInfo"class="user" data-name="sangseok" data-company="SK planet"
data-lang="korea" data-food="Noodle">
<span>고맙습니다</span>
</li>
저장값 접근 방식
●
JavaScript/DOM API 활용
var appDeveloperInfo = document.getElementById(‘appDeveloperInfo’);
var appDeveloperName = appDeveloperInfo.getAttribute(‘data-name’);
●
Jquery
jQuery.find(‘[data-name="sangseok"]’);
●
Jquery Mobile
$("li:jqmData(role=’name’")
21. JQM Data- attribute
JQM은 HTML 5 Data- attribute를 Widget 마다 정의하여 사용
●
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
●
초기화시 해당 data- attribute에 따라 element를 선택후 해당
element를 enhance를 수행함
– Extra markup 추가
– 새로운 CSS class 적용
– Event handler 등록
JQM 1.1.0에서는 data- attribute를 통한 enhance를 막는 기법
을 제공
●
data-enhance=``false’’
24. JQM Event Binding
jQuery의 live() 또는 bind() 를 사용
●
live(): jQuery selector에 현재 또는 미래에 match되는 모든 ele-
ment에 event handler를 attach
●
bind():jQuery selector에 현재 match되는 모든 element에 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);
}); });
25. JQM Method
Jquery.mobile object를 통해 각종 method를 제공함
●
$.mobile.changePage
●
$.mobile.loadPage: external page load
●
$.mobile.fixedToolbars.hide
●
$.mobile.silentScroll
– 주어진 Y위치로 onscroll trigger하지 않고 scroll
●
$.mobile.activePage
Full list는 아래에서 확인 가능
●
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
});
26. External page handling
현재 html이 아닌 별도의 html에 있는 page를 AJAX load후 DOM에
inject하는 기능
●
<head> 내부 부분 parsing 하지 않음
– JS 파일, <script> block, CSS를 load 하지 않음
●
Page-specific JavaScript 및 CSS는 직접 loading 해야함
<!DOCTYPE html>
– Page div 내에 포함 <html>
<head>
– <body> tag내에 포함 <title>My Page</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
후 pageInit에서 초기화 <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>
<div data-role="content"> <body>
<div data-role="page">
<a href="external.html" data-transition="pop">bar</a>
</div><!-- /content --> <div data-role="header">
<h1>I’am header</h1>
</div><!-- /header -->
<div data-role="content">
</div><!-- /content -->
</div><!-- /page -->
</body>
</html>
main.html external.html
27. 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) (1.1.1 기준)
jquery.mobile-1.0css(81KB) sencha-touch.js (367KB)
jquery.mobile-1.0.min.js(80KB) – 경량화 버전 sencha-touch.css (144KB)
jquery.mobile-1.0.min.css(48KB) – 경량화 버전 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 iOS3.0 +, Android 2.1+ ,Black Berry 6.0 +
6.0+ , Palm WebOS (1.4-2.0)/3.0,
공식 Homepage http://jquerymobile.com http://sencha.com/products/touch
개발 버전 1.1.0 2.0
개발 난이도 중 상
특이사항 개방성: 순수 Open Source 과제로 운영 Sench Touch Charts 유료버전 제공
Product 개발 지원을 위한 외부 전문 Consulting 업체 운영중 AT&T의 Browser 기반 HTML5 AppStore
라이선스 MIT (jQuery 프로젝트와 동일) Commercial S/W License (현재 무료)
GPL (jQuery 프로젝트와 동일) Commercial OEM License(유료)
Open Source License (GPL v3)
*Saas: Ruby기반의 CSS 생생 library
※Mozilla, Palm, BlackBerry, Adobe, Jive, DotMobi, Nokia, DeviceAtalas, filament
29. UI 명세서 중간 점검
29
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를 기준으로 위치를 고정
30. CSS position:fixed issue
CSS position:fixed 정의
●
element의 위치를 containing block이 아닌 window를 기준점으로 위치
를 정함
●
Web page 를 scroll하여도 위치가 고정되어 각종 메뉴구성에 쓰임
CSS position fixed 구현 방식
●
Android 2.3 이상, iOS 5.0이상 정상 동작
●
Android 2.2 이하 오동작 고정
– window기준으로 첫번째 rendering위치에 고정
●
IOS 4.0이하
– Web page의 끝 (마지막 element 다음)에 붙임
●
Android 2.3 삼성 단말 오동작
고정
31. CSS position:fixed 처리
JQM에서 position:fixed 처리 방식
●
Browser 엔진에서 지원시 사용
●
Browser 엔진에서 미지원시 처리 방식
– Scroll 시작시 사라지게하고 종료시 다시 그려줌
– Page 최상단과 하단에 position:static으로 붙임
●
중간 위치로 scroll 되어있을시 화면에 보이지 않게됨
문제점
첫번째 방식
– scroll시 JavaScript 수행을 중지시키는 경우 화면 update 문제 발생 (삼성 An-
droid 2.3 단말 포함)
– 지속적으로 깜빡 거려서 UX 저하
두번째 방식
– UX 관점에서 application이라기 보다는 web page의 느낌임
32. Fixed toolbar 지원 대안 1
overflow:scroll을 이용한 우회법
●
Fixed toolbar의 position은 fixed가 아닌 absolute, static, inline을 사용
하여 scroll하는 영역 위 아래에 고정
●
overflow:scroll을 이용하여 content 영역만을 scroll
문제점
●
overflow:scroll Android 2.3이하에서 미지원
●
IOS 4.0이상 지원하나 두손가락 gesture를 사용: UX 일관성 깨짐
●
지원이되더라도 화면 갱신 속도가 매우느림
position:fixed position:inline
content
viewport viewport
position:fixed position:inline content
overflow:scroll
IOS 5.0 부터는 -webkit-overflow-scrolling:touch 지원
34. iScroll 기능
iScroll의 기능
●
Pull to refresh
●
Pinch zoom
●
Scrollbar customize
●
Transition mode
– webkit-transform-timing-function: cubic-bezier 사용
●
Touch 미지원시 mouse fallback
Public method
●
refresh()
●
scrollTo(x, y, time, relative)
●
destroy
35. JQM내에서 iScroll활용
JQM에서 page는 visible하기 전까지 그것의 height값이 계산되어지지 않음
●
refresh 시점은 해당 page가 load되고 layout이 완료된후
기타 JQM specific한 동작 styling handling이 필요함
JQM widget plugin 활용 가능
●
https://github.com/watusi/jquery-mobile-iscrollview
제약 사항
●
webkit-transform을 사용하더라도 속도가 느려지는 경우 있음
●
scroller의 style은 CPU사용량이 최소한이 되도록 최적화 해야함
36. JQM 사용 Disclaimer
Android 3.0 이하 및 iOS 4.0이하에 적용시에는 단말별 동작 검증
필수
●
성능 문제
– Style 값에 따른 CPU 과다 사용
– <a> link 포함시 단말별도 반응속도 저하
●
Fixed element 동작 문제
●
Transition 지원 문제
– 1.1.0부터는 target에 따라 문제가 있으면 fade로 fallback
– 그러나 문제가 없다고 detect되는 단말에서 실제 구현상의 이슈,
또는 제조사 변경에 따라서 오동작 하는 경우가 다수임
37. Audio 기능 제공
Audio관련 상세 requirement
●
cross-platform으로 audio playback 지원
●
LCD off시 연속 재생 지원
●
Background mode 진입시 재생 지원
●
Playlist 지원
<audio> tag 지원
●
Android 2.1 및 2.2 미지원
38. IOS <audio> tag
IOS 4.0 >
●
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
●
autoplay is disabled by Apple on purpose
Browser in background mode (OEM customization)
●
JavaScript timer paused
●
Network paused
●
Script execution paused
●
SetInterval is suspended
39. Sound Manager 2
<audio> tag 와 Flash를 이용한 cross-platform audio playback 지원
●
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 - now 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!!
40. Playlist 연속 재생
LCD off 및 background 모드에서 연속재생 (Browser)
●
<audio> tag의 구현 및 browser의 동작 방식에 따라 연속 재생 기술
적으로 불가
●
기술 이슈 예
– LCD off mode시 JavaScript timer fire를 suspend
– 이미 DOM loading된 음악 재생은 가능하나, network를 통해
신규로 음악 loading 불가
현 시점에서 가장 안전한 방법
●
Hybrid application으로 변경
– Hybrid application내의 WebView에서 HTML app loading시
LCD off 모드에서 연속 재생 가능
41. Native-like GUI: Full screen
iOS의 Web App mode로 full screen 만들기
●
Full screen 만들기
– <meta name=”apple-mobile-web-app-capable” content=”yes>
●
Status bar 설정
– <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
●
시작 화면
– <link rel="apple-touch-startup-image" href="loading.png" />
Android에서 Web app mode
●
Full screen mode 미지원
●
Bookmark 등록 지원
http://developer.apple.com/library/safari/#documentation/appleapplications/reference/SafariHTMLRef/Articles/MetaTags.html
42. Native-like GUI: Full screen
URL bar hiding되는 browser에서 URL bar를 hiding시키는 조건
을 만족시키는 logic 구현
●
Android 및 Web app mode가 아닌 iOS Safari browser 적용
●
Web page의 height를 URL bar height와 window.innerHeight를 더한
값으로 set
var setupScroll = window.onload = function() {
if (ios) {
Disclaimer var height = document.documentElement.clientHeight;
if (iphone && !fullscreen) height += 60;
page.style.height = height + 'px';
●
Device 별 URL bar 크기 차이 } else if (android)
page.style.height = (window.innerHeight + 56) + 'px'
●
URL bar hiding animation }
setTimeout(scrollTo, 0, 0, 1);
도중 window는 계속적으로 resize 됨 };
●
URL bar hiding animation도중 멈추는 현상 발생
(삼성 Galaxy Note/HD)
https://gist.github.com/1172490
43. 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
49. WebKit Open Source Project
Apple, Google 주도의 Open Source Project
Committer/reviewer 분포 Reviewer Committer
Web 분야 투자/Leadership 간접 지표 Apple 39 6
Google 24 32
Committer 자격 삼성전자 2
10-20 good patch 총합 83 60
3명의 reviewer로부터 추천 국내 committer: 4명
삼성전자: 2명 (EFL)
Reviewer 자격 Company100: 1명 (Brew)
Collabora: 1명(Gtk)
최소 80 good patch
4명의 reviewer로부터 추천 (최소 한명은 다른 회사)
약 3백만 line으로 분야별로 전문 reviewer 활동
50. WebKit 구조
WebKit은 Browser아닌 Web표준 처리를 위한 LIBRARY 집합
Mozilla Firefox, Google Chrome는 Browser가 Open Source
UI, Graphics, network등은 platform 별 별도 구현
대부분의 성능의 격차는 port 구현에서 발생함
HW 가속, Image Caching, API등은 port 별 구현
Webkit open source 범위
Mac port는 미공개
메모리
Browser GUI DB Network
관리
WebView (Widget, API)
HTML, CSS, JavaScript Mac Efl Gtk Qt Android
JavaScriptCore Plug
WebKit WebCore -in
(SFX, V8)
Platform Port (HW 가속 포함)
Native Native Cairo/Skia OpenGL ES
Windowing Widget (2D graphics) (3D graphics) Mac Efl Gtk Qt Android
WebKit Graphics back-end 구조 Native Platform
Webkit 기반 Browser
51. Chromium Browser
WebViewClient RenderProcess WebCoreSupport
Browser Process
TabContents
URL Bar JS
Gtk WebCore
RenderViewHost FrontEnd
Widge Styl
t e
RenderProcessHost Graphic Parser
V8 Rule DO
s Render
Web Page Resource s M
Gtk Layer Tree
DispatcherHost Tree
Widge Tree
JIT Loader
t IPC Channel
Glib main loop (Event Queue)
GPU Platform
HTTP RenderView
Process File/DB
stack Port
IPC Channel Resource Dispatcher ResourceLoaderBridge
Plugin NPAPI:: IPC
PluginHost Channel
Process
UI FW Skia (2D graphics) Gtk
X server compositor
OpenGL ES / EGL
GPU Memory GPU Process Window Buffer Frame Buffer
URL bar
Webview
Indicator
52. Android Browser
Multi-threaded
Browser Process
WebViewClient WebViewCoreThread WebCoreSupport
Main Thread JS
FrontEnd
WebCore
Tool Bar Styl
Webview Partially
Graphic e Parser
Canvas Cached V8 Rule DO
s Render
DOM s M
Layer Tree
Node Tree
Tree
JIT Loader
Canvas
PictureSet
Platform
RenderView
Port
Message Handler (Event Queue) Message Handler
UI FW Skia (2D graphics) Gtk
Surface Manager compositor
OpenGL ES / EGL
GPU Memory Window Buffer Frame Buffer
Indicator
53. DOM과 Render Tree 개괄
DOM Tree HTMLDocument RenderView Render Tree
2. addChild() 6. addChild()
3. rendererIsNeeded? YES
1. Element 생성 HTMLHtmlElement RenderBlock 4. RenderBlock 생성
5. setRender()
HTMLHeadElement
rendererIsNeeded? NO
HTMLTitleElement
http://image.google.com HTMLStyleElement
<html> HTMLScriptElement
<head>
<title>Google</title>
<style>…</style> HTMLBodyElement RenderBlock
<script>…</script>
</head>
HTMLDivElement RenderBlock
<body>
<div>
<nobr> HTMLElement(nobr) RenderInline
<span>
<a href=“http://news.google.com”>News</a> HTMLElement(span) RenderInline
</span>
<span>…</span>
</nobr> HTMLAnchorElement RenderInline
</div>
</body>
</html> Text RenderText
HTMLElement(span) RenderInline
54. WebKit Rendering Basics(1/4)
내부 Data Structure
<html> Document
<head> Render- Render-
</head> View RootLayer
<body> <html>
<p> hello</p> 조건별 Layer 생성
<div class=“page” >
<p>world</p>
<div>
</body>
parsing DOM node
<head> <body>
</html> attach
.page { RenderLayer1
position: absolute; <p> <div>
width: 100%;
height: 100%;
-webkit-transform: translate3d(0, 0, 0); Render- RenderText:
} hello <p> Text:”Hello” ”World”
world
HTML/CSS file DOM Tree Render Tree RenderLayer Tree
55. WebKit Rendering Basics(2/4)
내부 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
Render- Render- Hello
View RootLayer
World
RenderBoxModelObject::
requiresLayer()
Z ordering
RenderLayer GraphicLayer
Render-
Render-
Text:”World
Text:”Hello”
”
Render Tree RenderLayer Tree GraphicsLayer Tree
(Texture on GPU)
56. WebKit Rendering Basics(3/4)
Painting 절차
SW path
하나의 graphic buffer를 할당
Z order에 따라 뒤에서 앞으로 칠함 Hello
Hello를 주어진 buffer에 paint World
World를 Hello를 paint한 buffer에 칠함 GraphicsContext: Graphic Buffer
HW accelerated path: Accelerated Compositing by GPU
CPU graphics buffer와 GraphicsLayer 별 GPU buffer 생성
Layer 별로 painting
모든 결과를 sync하여 compositing
Hello Hello
World World
Compositing
by GPU (Open GL ES)
GraphicsContext: GraphicsContext:
Graphic Buffer on CPU Graphic Buffer on GPU
57. WebKit Rendering Basics(4/4)
HW accelerated path: Accelerated Compositing by GPU
CSS 2D/3D transformation시 “World”를 animation 각도에 따라 매번 다시 paint
하지 않고 만들어진 texture를 GPU로 회전 후 기타 Layer와 compositing 수행
Hello Hello
Wo Wo
r ld r ld
Compositing
by GPU (Open GL ES)
GraphicsContext: GraphicsContext:
Graphic Buffer on CPU Graphic Buffer on GPU
장점
속도가 CPU 대비 “order of magnitude”로 빠름
3D transformation은 Accelerated Composting이 enable되어 있을때만 사용 가능
단점
메모리 사용량 증가: GPU memory를 별도로 할당
iOS 및 Android 4.0이상에서 지원
58. Silky Smooth Scroll 기술(1/3)
“60 frame/sec” rule: 인간의 눈 고려시 최적 값
최소 16 msec 마다 한번씩 화면 갱신 필요
Reflow 연산: 50 msec~(600MHz@ARM Coretex-A8)
주어진 DOM Tree에서 invalidate된 화면을 다시 re-paint
Finger touch
viewport
59. Silky Smooth Scroll 기술(2/3)
BackingStore
한번의 scroll로 이동 가능한 영역에 대해서 pre-rendering된 결과를 image
로 caching
사용자 Scroll시 pre-rendering된 image의 일부를 cut-n-paste를 하여
viewport로 복사 Reflow/Repaint 제거
Single Image Buffer
60. Silky Smooth Scroll 기술(3/3)
BackingStore
한번의 scroll로 이동 가능한 영역에 대해서 pre-rendering된 결과를 image로 caching
사용자 Scroll시 pre-rendering된 image의 일부를 cut-n-paste를 하여 viewport로 복사 Re-
flow/Repaint 제거
Render- Render-
View RootLayer
Z ordering
RenderLayer GraphicLayer
Render- Viewport보다 큰 영역을
Render-
Text:”Hello”
Text:”World 미리 rendering해서 image cache를 해둠
” 사용자 panning시 이미 rendering된 이미지를
복사해주기만 함
62. 2D/3D Animation
[RULE] CSS 2D/3D transforms를 이용한 2D/3D animation 구현은 HW 가속 Accel-
erated Compositing 기능이 제공 되는 Mobile OS 에서만 사용한다
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
JavaScript를 통한 지원 여부 검사 방법
지원 여부 X O O X§ X§ X§ X O
User agent를 통해 Mobile OS 버전을 알아내서 활용 가능
해당 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 활용 (추천)
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 만 적용 가능
63. 2D/3D Animation
[RULE] CSS 2D/3D transforms를 이용한 2D/3D animation 구현은 HW 가속 Accel-
erated Compositing 기능이 제공 되는 Mobile OS 에서만 사용한다
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
JavaScript를 통한 지원 여부 검사 방법
지원 여부 X O O X§ X§ X§ X O
User agent를 통해 Mobile OS 버전을 알아내서 활용 가능
해당 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 활용 (추천)
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 만 적용 가능
64. 2D/3D Animation
[RULE] Animation이 수행되는 layer 수를 최소화 하고 크기를 power of 2로 adjust 하
자. Layer 수의 증가는 animation시 사용하는 GPU메모리 사용량을 증가시킴
Open GL ES Texture 생성 제약 조건※
Texture의 width와 height는 power of 2 이어야 함
2, 4, 8, 16, 32, …, 1024
PowerVR chip의 PVRTC compressed image 사용시 정사각형 이어야 함: iOS
device 계열에서 사용 http://joehewitt.com/2011/10/05/fast-animation-with-ios-webkit
Max size limit 있음
OpenGL ES 1.0 SGX: 1024x1024
OpenGL ES 2.0 SGX: 2048x2048
Layer의 크기가 257x257이면 실질적으로는 512x512 크기의 texture를 생성하게 됨
다수의 layer를 위와 같이 생성시 비효율적인 메모리 사용 증가
※ Graphics Chip Vendor 별로 특성 확인 필요
65. 2D/3D Animation
[RULE] Animation을 수행하는 영역은 as simple as possible 하
게 유지하자
Animation 대상 block이 painting 비용 관점에서 복잡해질수록
Animation시 사용하는 Texture를 초기 생성하는 지연증가로 An-
imation 개시 지연 발생
Not simple 의미: !(painting cost가 높음)
CSS filter, shadow, canvas, SVG, 과도한 DOM node 개수, scaled된
image 등
비용증가
Texture 생성 시간 증가
일반 text animation 개시 시간 증가 Blurred text
이해를 하고 꼭 알고 쓰자
66. 2D/3D Animation
[RULE] Animation 시나리오상 animation 대상 block은 그것의 visual
change가 발생하지 않도록 작성하자
변경시 마다 texture를 재생성해야하고 texture를 caching 하여 재활용 하
는 mobile OS에서는 cache 효율성이 낮아짐
http://www.w3schools.com/css3/tryit.asp?filename=trycss3_transition2
width, height가 변경되는 경우와 그렇지 않은 경우 비교
Animation 도중 text blurring 시나
리오
이해를 하고 꼭 알고 쓰자
67. HW 가속 Layer 이용
image zoom in/out시 잘 보이기 위해서 그것을 HW composit-
ing layer로 mapping 가능
해당 image에 아래 CSS 적용
-webkit-transform:translate3d(0,0,0) 별도 layer에 map-
ping
resource 사용량이 늘어남
68. CSS overflow property
[RULE] CSS의 overflow:scroll 속성의 사용은 신중히하자
Platform 별 대처 방식 div
{
iOS에서는 two finger로 scroll 가능 width:150px;
height:150px;
-webkit-overflow-scrolling: touch
overflow:scroll;
iOS 5 부터 지원: native 수준 성능 제공 }
Android는 one finger scroll 가능
3.0 이후 버전만 scroll 지원 (2.3 이하 미지원)
단점
일반 화면 scroll에 비해 속도가 느림
BackingStore에 cache 되지 않고 매번 Render Tree으로부터 다시 paint
iOS 5와 Firefox는 별도의 Layer로 구성되고 layer별 BackingStore 지원으로 빠르나 메모리 사용
량 증가
poor discoverability: 사용자가 scrollable 여부 인지하기 힘듦
화면 자산때문에 scroll bar를 지원하지 않음
69. Layout 발생 및 비용 분석
[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,856개)
Layout 발생 조건
Browser window resize, Orientation 변경
style information 정보 요청
DOM 변경: Adding, removing, updating nodes
display property, CSS box model 값 변경
Desktop 에서의 zooming 및 scrolling
Mobile 단말에서 layout 없이 zoom factor에 따라 content를 repaint
70. Layout 비용 절감
[RULE] styling 변경은 꼭 필요시, 꼭 필요한 부분만 국소적으로 하라
Text 크기 변경, margin/padding/border 크기 변경, font type 변경등
은 전체 또는 부분 page layout 수행을 야기한다
Layout후 해당 부분은 다시 repaint를 수행
CSS Box Model
Repaint 만 발생하는 경우 (layout 미 발생)
Visibility, colors, transforms, backgroud images, transparency
71. CSS 삽입 위치
[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까지가 지연이 된다
72. CSS 기능중 신중함이 필요한 기능
[RULE] 하기 CSS 기능은 CPU 사용률이 매우 높기 때문에 신중히
사용하자
Rounded corners
Box-shadow, Text-shadow
Shadowing은 static bitmap이미지가 아니고 매번 repaint때
마다 evaluate 됨
Backgroud-position
Background-repeat
Multiple background images
Border-image
Gradients
73. Rounded Corners 표현
[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
74. Shadows
[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
75. Gradient
[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/
76. CSS property 접근
[RULE] JavaScript를 통한 CSS Property의 접근은 page loading이 완료된 시
점에서 하자.
E.g. onload event후
Page loading 중 CSS property 접근시 문제점
JavaScript를 통한 CSS property의 접근은 WebKit에서 가장 비싼 연산인
layout() 강제함: 수백 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()
{
77. JavaScript loading 최적화
[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 ren-
dering을 block 시킴
HTML parsing 도중 inline 또는 external JavaScript를 만나면
Inline JavaScript는 parsing후 호출이 되었으면 실행
External JavaScript는 network을 통해 적재, parsing후 호출이 되었으면 실행
Loading,parsing, 실행중 계속적인 HTML parsing은 suspend가 기본 동작
Webkit에서는 속도 향상을 위해 image object는 speculative하게 loading을 수행
https://bugs.webkit.org/show_bug.cgi?id=17480 (WebKit PreloadScanner)
이는 JavaScript의 수행으로 DOM 변경이 가능하므로 JavaScript의 수행 완료가 보장되어야만
하기 때문임
78. document.write() 사용 제한
[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
79. CSS @import 제약사항
[RULE] <link> tag를 사용하여 CSS를 load하고 CSS @import를
사용하지 말아라
Browser는 일반적으로 import 된 stylesheet을 병렬 loading을
지원 하지 않음
81. Google Page Speed
동작
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.html
사용성
Mobile 또는 desktop 용 Web site 제작시 사용 가능
Local에 설치되는 web app은 다수 적용 가능
82. Page Speed: jQuery mobile
82
http://jquerymobile.com/demos/1.0/docs/lists/lists-formatting.html
22점
83. 압축 사용
Web server를 Content-Encoding을 모든 compressible re-
source (HTML, CSS, JavaScript)에 gzip 적용
150-100bytes 이상일 경우 compression/decompression
overhead를 상쇄 가능
84. JavaScript/CSS minification
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 SettingsusernameLocal
SettingsTemppage-speed-[css | javascript | images]
Mac OS X: /Users/username/Library/Caches/page-speed-[css | javascript | im-
ages]/
92. 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 개선 사례
http://googlecode.blogspot.com/2009/09/gmail-for-mobile-html5-series-reducing
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/
93. 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-Polyfills
http://www.webkit.org/blog/156/queryselector-and-queryselectorall/