410 likes | 863 Views
APP-162T. Building high performance Metro style apps using HTML5. Mathias Jourdain Principal Development Lead Microsoft Corporation. Agenda. Understand how to improve your app launch Discover why and how to conserve system memory Learn how to keep your app responsive
E N D
APP-162T Building high performance Metro style apps using HTML5 Mathias Jourdain Principal Development Lead Microsoft Corporation
Agenda • Understand how to improve your app launch • Discover why and how to conserve system memory • Learn how to keep your app responsive You’ll leave with examples of how to • Make the performance of good apps great • Measure the time your app took to launch and whether its UI ever became unresponsive
HTML app platform Internet Explorer App container HTML host process TAB App code Web platform App code Webplatform Windowsruntime
Tips & tricks that still work • For safe dynamic content, use innerHTML to create your DOM • Link CSS stylesheets at the top of the page, not at the bottom • Avoid inline JavaScript and inline CSS styles • Don’t parse JSON by hand, use JSON.parse • To hear more, view: [PLAT-386T] 50 performance tricks to make your Metro style apps and sites using HTML5 faster
App launch Splash screen App visible Loading and parsing of HTML, JS, CSS Ready for user New host process Windows Runtime "activated" event "DOMContentLoaded" event Navigation Tile click
Optimize your landing page • Rely on packaged content and local data • Use local images scaled to the right size • Use WinJS fragments to load parts of your app on demand • Defer parsing of unneeded HTML content • Delays JavaScript • Keeps your DOM small: look-up and manipulations are quicker
Further optimizations • Defer some initialization to after the splash screen • Start network downloads after initialization • Delay loading databases • Consolidate small JS files that are related into larger files • If you need more time, use an extended splash screen
Process state transitions App is not notified when terminated App has 5s to work after suspend message suspending Running Suspended Terminated Low memory Applaunch resuming App is notified when resumed Splash screen Code runs No process Code runs No code runs
demo Tile Puzzle Memory consumption
Manage your resources • Keep a lightweight DOM • Release expensive content, such as media elements, as soon as they are no longer needed • Help the garbage collector • Avoid circular references between your elements and JavaScript code • Review how you use your Object URLs • On suspend, free resources that are easy to recreate • Use media content from the user at the screen resolution
How to use athumbnail of an image • // Open File Picker • var picker = new Windows.Storage.Pickers.FileOpenPicker(); • picker.fileTypeFilter.replaceAll([".jpg", ".png"]); // Pick an image file picker.pickSingleFileAsync() .then(function (file) { varproperties = Windows.Storage.FileProperties.ThumbnailMode; return file.getThumbnailAsync(properties.singleItem, 1024); }) .then(function (thumb) { varimgTag = document.getElementById("imageTag"); imgTag.src = URL.createObjectURL(thumb, false); }); // Pick an image file picker.pickSingleFileAsync() .then(function (file) { varimgTag = document.getElementById("imageTag"); imgTag.src = URL.createObjectURL(file, false); });
demo Tile Puzzle with a thumbnail Memory consumption Using the thumbnail APIs to obtain screen-size images
The lighter you are, the less likely your app will be terminated while suspended. Consider the impact of your app on the system.
CPU activity UI thread 0s 1s 2s 3s Animation Launch User input
Example of app execution JavaScript Compute layout User input events Update app logic Update view (DOM) Timers Callbacks Time on the UI thread
Responsiveness pattern #1: use asynchronous APIs • Synchronous API calls that wait on a resource block the UI thread • Asynchronous APIs let your code continue to run while the OS processes your request in the background • Use asynchronous APIs whenever available UI thread UI thread
How to make an asynchronous XHR call • varxhr = new XMLHttpRequest(); • xhr.onload= function(){ • // The request completed successfully • }; • xhr.onerror = function(){ • // The request failed with an error • }; • xhr.open("GET", “http://www.contoso.com/page.aspx", true); • xhr.send(null);
How to pick afile asynchronously with a Promise • // Instantiate the file picker • var picker = new Windows.Storage.Pickers.FileOpenPicker(); • // Restrict the files shown to JPG and PNG images • picker.fileTypeFilter.replaceAll([".jpg", ".png"]); • // Launch the file picker, and execute one of the callbacks once the • // user has selected an image • picker.pickSingleFileAsync().then( • function(file) { • //code to execute when a file is picked • }, • function (error) { • //code to execute when an error occurs • } • );
Responsiveness pattern #2: avoid time intensive calculations • Fast interactive touch apps react to users within 100 ms • Anything more, the user notices • Be careful of expensive operations on the UI thread…
demo 5-in-a-Row Calculations on the UI thread impact responsiveness
Break apart expensive work • Don’t run long operations on the UI thread • Timers and Intervals are inefficient • Do break up long operations with setImmediate UI thread UI thread UI thread
Web Workers • Many devices have multiple cores that are underutilized • With Web Workers you can schedule work on a different thread • Offload main business logic to a Web Worker to keep the UI thread focused on UI UI Thread Worker Thread
demo 5 in-a-row with a Web Worker Calculations on the UI thread impact responsiveness
Responsiveness Pattern #3: avoid extra work • Most monitors update at 60 FPS, every 16.7 ms • Use requestAnimationFrame to only draw when needed UI thread UI thread
Windows Animation Library • Consistent animations across apps are key to a great user experience • With CSS3 transitions and animations, you can avoid frequent and expensive re-layouts of your page and benefit from hardware tie-in • Use the Windows Animation Library to make your app feel built for Windows and get the perf of CSS3 • To hear more, view: [APP-206T] Bring apps to life with Metro style animations in HTML5
Tools for building touch apps • App templates • Controls: ListView, AppBar, select control, etc. • Scrolling and zooming views • Gesture events • Pointer events • Gesture recognizers • To hear more, view: [APP-185T] Make great Metro style apps that are touch-optimized using HTML5
Build lasting impressions, make performance a pillar of your app
Summary • Tune your app launch time to create great first impressions • Keep your app alive by minimizing your memory footprint • Be responsive, don’t block the UI thread
Related sessions • [APP-185T] Make great Metro style apps that are touch-optimized using HTML5 • [APP-206T] Bring apps to life with Metro style animations in HTML5 • [PLAT-376T] Building offline access in Metro style apps and websites using HTML5 • [PLAT-386T] 50 performance tricks to make your Metro style apps and sites using HTML5 faster • [APP-409T] Fundamentals of Metro style apps: how and when your app will run
© 2011 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.
Tool #1: how to calculate activation times • Windows.UI.WebUI.WebUIApplication.addEventListener("activated", onActivation, false); • function onActivation(e) { • // Snap when the activation event callback was called back • varnow = new Date().getTime(); • // Calculate the times between the various events • varpage_load_time = performance.timing.domContentLoadedEventStart - performance.timing.navigationStart; • varpage_activated_time = now - performance.timing.navigationStart; • // Update the DOM to reflect the times calculated • document.getElementById("domcontentloaded").innerText = page_load_time + "ms"; • document.getElementById("activation").innerText = page_activated_time + "ms"; • }
Tool #2: how to detect UI delays • varlastUIDelayTime = 0; • varmaxUIDelayTime = 0; • function renderLoop() { • varnow = new Date().getTime(); • if (lastUIDelayTime != 0) { • varcurrentUIDelay = now - lastUIDelayTime; • if (currentUIDelay > maxUIDelayTime) { • maxUIDelayTime= currentUIDelay; • // Display the new maximum • document.getElementById("maxuidelay").innerText = maxUIDelayTime + " ms"; • } • } • // Remember the last time this function was scheduled, and reschedule • lastUIDelayTime= now; • msRequestAnimationFrame(renderLoop); • }
Tool #3: how to calculate frames per second • varlastUIRefreshFPS= 0; • varframeCounter= 0; • function renderLoopFPS() { • varnow = new Date().getTime() % 1000; • if (now < lastUIRefreshFPS) { • // Display the FPS • document.getElementById("fps").innerText= frameCounter+ " frames"; • // Reset the FPS counter • frameCounter= 0; • } • // Increment the FPS counter • frameCounter+= 1; • lastUIRefreshFPS= now; • msRequestAnimationFrame(renderLoopFPS); • }
© 2011 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.