Estelle Weyl | @estellevw | Github | Press to advance, 2 for comments, 4 to read/write notes.

Mobile: Web Performance

HTML5 and CSS3 for the Real World HTML5: The Definitive Guide MObile HTML5 Web Performance Daybook

Slides: estelle.github.com/mobileperf
Name: Estelle Weyl
Blog: standardista.com
Twitter: @estellevw

How this slide deck works

Click on the #4 to show some notes stored with local storage

Press to advance and show next comments

Press to go back

Or navigation with buttons or browser history

Files will be at estelle.github.com/mobileperf

phones

Houston, we've got a problem

Open in new window

Web Performance Optimization

  • stylesheets at the top
  • scripts to the bottom
  • minify javascript and css
  • External scripts and styles(?)
  • reduce DNS lookups
  • gzip everything
  • cache what you can

Tools: YSLOW & PageSpeed

What that means....

<!DOCTYPE HTML>
<html>
 <head>
   <meta charset="UTF-8">
   <title>Titles are good for SEO</title>
   <link rel="stylesheet" href="prettyWhenItLoads.css"/>
 </head>
 <body>
   <!-- lots of good content -->
   <script src="dontBlockHTMLandCSS.js"></script>
 </body>
</html>

Resource: YSLOW

  • Make fewer HTTP requests

    Decreasing the number of components on a page reduces the number of HTTP requests required to render the page, resulting in faster page loads. Some ways to reduce the number of components include: combine files, combine multiple scripts into one script, combine multiple CSS files into one style sheet, and use CSS Sprites and image maps.

  • Avoid empty src or href

    You may expect a browser to do nothing when it encounters an empty image src. However, it is not the case in most browsers. IE makes a request to the directory in which the page is located; Safari, Chrome, Firefox 3 and earlier make a request to the actual page itself. This behavior could possibly corrupt user data, waste server computing cycles generating a page that will never be viewed, and in the worst case, cripple your servers by sending a large amount of unexpected traffic.

  • Compress components with gzip

    Compression reduces response times by reducing the size of the HTTP response. Gzip is the most popular and effective compression method currently available and generally reduces the response size by about 70%. Approximately 90% of today's Internet traffic travels through browsers that claim to support gzip.

  • Put CSS at top

    Moving style sheets to the document HEAD element helps pages appear to load quicker since this allows pages to render progressively.

  • Put JavaScript at bottom

    JavaScript scripts block parallel downloads; that is, when a script is downloading, the browser will not start any other downloads. To help the page load faster, move scripts to the bottom of the page if they are deferrable.

  • Avoid CSS expressions

    CSS expressions (supported in IE beginning with Version 5) are a powerful, and dangerous, way to dynamically set CSS properties. These expressions are evaluated frequently: when the page is rendered and resized, when the page is scrolled, and even when the user moves the mouse over the page. These frequent evaluations degrade the user experience.

  • Reduce DNS lookups

    The Domain Name System (DNS) maps hostnames to IP addresses, just like phonebooks map people's names to their phone numbers. When you type URL www.yahoo.com into the browser, the browser contacts a DNS resolver that returns the server's IP address. DNS has a cost; typically it takes 20 to 120 milliseconds for it to look up the IP address for a hostname. The browser cannot download anything from the host until the lookup completes.

  • Minify JavaScript and CSS

    Minification removes unnecessary characters from a file to reduce its size, thereby improving load times. When a file is minified, comments and unneeded white space characters (space, newline, and tab) are removed. This improves response time since the size of the download files is reduced.

  • Avoid URL redirects

    URL redirects are made using HTTP status codes 301 and 302. They tell the browser to go to another location. Inserting a redirect between the user and the final HTML document delays everything on the page since nothing on the page can be rendered and no components can be downloaded until the HTML document arrives.

  • Remove duplicate JavaScript and CSS

    Duplicate JavaScript and CSS files hurt performance by creating unnecessary HTTP requests (IE only) and wasted JavaScript execution (IE and Firefox). In IE, if an external script is included twice and is not cacheable, it generates two HTTP requests during page loading. Even if the script is cacheable, extra HTTP requests occur when the user reloads the page. In both IE and Firefox, duplicate JavaScript scripts cause wasted time evaluating the same scripts more than once. This redundant script execution happens regardless of whether the script is cacheable.

  • Reduce the number of DOM elements

    A complex page means more bytes to download, and it also means slower DOM access in JavaScript. Reduce the number of DOM elements on the page to improve performance.

  • Avoid HTTP 404 (Not Found) error

    Making an HTTP request and receiving a 404 (Not Found) error is expensive and degrades the user experience. Some sites have helpful 404 messages (for example, "Did you mean ...?"), which may assist the user, but server resources are still wasted.

  • Avoid AlphaImageLoader filter

    The IE-proprietary AlphaImageLoader filter attempts to fix a problem with semi-transparent true color PNG files in IE versions less than Version 7. However, this filter blocks rendering and freezes the browser while the image is being downloaded. Additionally, it increases memory consumption. The problem is further multiplied because it is applied per element, not per image.

  • Do not scale images in HTML

    Web page designers sometimes set image dimensions by using the width and height attributes of the HTML image element. Avoid doing this since it can result in images being larger than needed. For example, if your page requires image myimg.jpg which has dimensions 240x720 but displays it with dimensions 120x360 using the width and height attributes, then the browser will download an image that is larger than necessary.

  • Make favicon small and cacheable

    A favicon is an icon associated with a web page; this icon resides in the favicon.ico file in the server's root. Since the browser requests this file, it needs to be present; if it is missing, the browser returns a 404 error (see "Avoid HTTP 404 (Not Found) error" above). Since favicon.ico resides in the server's root, each time the browser requests this file, the cookies for the server's root are sent. Making the favicon small and reducing the cookie size for the server's root cookies improves performance for retrieving the favicon. Making favicon.ico cacheable avoids frequent requests for it.

Click list item for details.

Resource: Page Speed

  • Leverage browser caching
  • Enable compression
  • Defer parsing of JavaScript
  • Minimize request size
  • Specify a cache validator
  • Optimize images
  • Minify JavaScript
  • Minify HTML
  • Specify image dimensions
  • Specify a character set
  • Specify a Vary: Accept-Encoding header
  • Reduce request serialization
  • Eliminate unnecessary reflows
  • Avoid long-running scripts
  • Avoid CSS @import
  • Avoid bad requests
  • Enable Keep-Alive
  • Make landing page redirects cacheable
  • Minify CSS
  • Minimize redirects
  • Optimize the order of styles and scripts
  • Put CSS in the document head
  • Remove query strings from static resources
  • Serve resources from a consistent URL
  • Serve scaled images

Device limitations!

  • Battery
  • Latency
  • Memory
  • Responsiveness

Phones aren't Laptops

More powerful browsers. Less powerful CPUs

Batteries

Who Killed My Battery: Analyzing Mobile Browser Energy Consumption

Narendran Thiagarajany
naren@cs.stanford.edu
Gaurav Aggarwaly
agaurav@cs.stanford.edu
Angela Nicoara*
angela.nicoara@telekom.com
TL;DR;

Images

  • JPEGs GIFs and PNGs
  • Images ⇒ energy consumption
  • Rendering energy is proportional to # and size of images.

JavaScript

  • Render cost: JS (and CSS) images
  • Dynamic JS: ⬆ rendering cost (can't be cached).
  • JS (download, parsing & executing) can be the most energy consuming web page component

Images

Use background images, instead of foreground images.

Background images are first rendered with image data send to Core Animation. Safari doesn't render <img> first. The decoded image file is sent, as is, pre-rendered, to the Core Animation as a new layer. Foreground images is sent to Core Animation as image data which it has to keep in graphics memory. This uses more memory.

CPU used to decode images

Scaled: 1,850 milliseconds

Right-sized: 625 milliseconds

  • blue = CPU used to decode
  • green = FPS (more is better)
  • purple = rendering
PhysicsOfFast

JavaScript!

  • All scripts loaded and parsed (even if not used)
  • Reduce JS to only what is needed
  • Are libraries really necessary?
    • Include only functions used by page to reduces energy use.
    • Goal of most: equalize across browsers
      (not necessry in mobile space)
    • Libraries simplify web development, but increase energy use.
    • You don't need a framework for that

Battery Consumption

CPU Drains the battery. Avoid using it!

  • Avoid Reflows (and repaints)
  • Minimize JavaScript (size and activity)
  • No JavaScript Animations
  • Avoid WebGL
  • Implement what you learn today
  • Avoid loading resources you don't need
  • Manage memory

Latency

DNS / HTTP Requests

COmputer asks DNS server for IP address, then goes to IP to get website

Each host is a different lookup!!

Latency

Computer asks DNS server for IP address, then goes to IP to get website
  • Issue: Requests take longer to complete
  • Solution: Reducing requests improves performance

Step 1: Don't Redirect!!!!

Step 2: Reduce Requests

Sprites

Favicon Image Sprite

Best Practices (for desktop)

<!DOCTYPE HTML>
<html>
 <head>
   <meta charset="UTF-8">
   <title>Titles are good for SEO</title>
   <link rel="stylesheet" href="prettyWhenItLoads.css"/>
 </head>
 <body>
   <!-- lots of good content -->
   <script src="dontBlockHTMLandCSS.js"></script>
 </body>
</html>

Reduce HTTP requests

<!DOCTYPE HTML>
<html>
 <head>
   <meta charset="UTF-8">
   <title>Titles are good for SEO</title>
   <style id="keyword">
     /* lots of styles */
   </style>
 </head>
 <body>
   <!-- lots of good content -->
   <script id="otherKey">
     /* JS that makes site work
   </script>
   <script>
     /* localStorage &  cookies script*/
   </script>
 </body>
</html>

Memory

High memory usage causes a slow UI

When you are out of memory, you are out of memory

Browser crashes to free up memory

Memory

Device Memory
iPhone 3G128MBiphone
htc inspire
iPad
iPhone 3GS256 MB
iPhone 5/5S/61 GB
HTC Inspire768 MB
iPad 1256 MB
iPad 3/41 GB
iPod Touch (4)256 MB
Samsung Galaxy Note Edge3GB
Intex Cloud FX128 MB
MacBook Pro16 GB

Mobile Norm: 512MB of RAM, with 1GHz Processor

PC Norm: 8GB+ RAM

Developing without mobile in mind
leads to sloppy App Dev

Browser shares Memory

Running Services
Other73MB Avail: 255MB + 182MB in 21
Calendar8.4MB
Process:com.htc.bgp
ObexService31:52:14
Started by application: Touch to stop
AT&T Navigator8.4MB
Process: com.telnav.app.android.congular
ResoucePreLoaderRestarting
Started by application: Touch to stop
AT&T Spots2.4MB
Process: com.matchboxmobile.wasp
WispService31:52:14
Started by application: Touch to stop
Media4.1MB
Process: android.process.media
DownloadService31:52:14
Started by application: Touch to stop
PVWmdrmService2.2MB
Process: com.pv.wmdrmservice
PVWmdrmService31:52:14
Started by application: Touch to stop

Sprites: Best choice?

Favicon Image Sprite

Not enough to GZip

Rendered media are still the same size.

  • Reduce File Size
  • Reduce Image Size

Video, Audio, Images and Text can be compressed to save bandwidth, but they're uncompressed in the browser.

Reduce File Size

images alpha saving 64% file size

Image Alpha

Reduce Image Size

Don't send big images to small screens?
Images 1024px or bigger are too big for memory

sencha uses user agent sniffing,not browser size

Change your user agent and click on links above

Right-size your images

Scaled: 1,850 milliseconds

Right-sized: 625 milliseconds

  • blue = CPU used to decode
  • green = FPS (more is better)
  • purple = rendering
PhysicsOfFast

Object + Media Queries + SVG + CCimg

media queries

<link rel='stylesheet'
media='screen and (min-width: 320px) and (max-width: 480px)'
href='css/smartphone.css' />
@media screen and (max-width: 480px){
  body {
    background-image: url(small/bgimage.jpg);
  }
}
@media screen and (min-width: 481px) and (max-width: 960px){
  body {
    background-image: url(medium/bgimage.jpg);
  }
}
@media screen and (min-width: 481px) and (max-width: 960px),
screen and (min-width:540px) and (-webkit-min-device-pixel-ratio: 2){
  body {
    background-image: url(large/bgimage.jpg);
  }
 } 

Resource: What can you query

  • (min/max)-width: viewport width
  • (min/max)-height: viewport height
  • (min/max)-device-width: screen width
  • (min/max)-device-height: screen height
  • orientation: portrait(h>w) | landscape(w>h)
  • (min/max)-aspect-ratio: width/height
  • (min/max)-device-aspect-ratio: device-width/height
  • (min/max)-color:
  • (min/max)-color-index:
  • (min/max)-monochrome: 0 | 1+
  • (min/max)-resolution: 72dpi | 100dpcm
  • scan: progressive | interlace (tv)
  • grid: 0 | 1 (grids (like tty) or bitmap)
  • See Media Queries Spec

Resource: How do you query it?

Media Query Syntax/Punctuation

media="only print and (color)"

media="only screen and (orientation: portrait)"

media="not screen and (color)"

media="print, screen and (min-width: 480px)"

CSS Masking

jpeg plus framemask less than transparent png
88KB + 4KB < 551KB

div {
  background-image:url(images/frame.jpg);
  -webkit-mask: url(images/framemask.png);
}

Masking example

Download Zip

Is CSS3 the Solution?

Properties

  • rounded Corners
  • box-shadow
  • text-shadow
  • background-position
  • background-repeat
  • multiple background images
  • border-image
  • gradients
  • @media queries

Benefits

  • Fewer HTTP Requests
  • Updatable
  • Scalable
  • Transitionable
  • Animatable
  • Fewer DOM Nodes

CSS3 ISN'T always the Solution!

UI Features can ruin your web app

  • Enlarged Fonts
  • Box Shadow (inset)
  • Text Indent
  • Gradients
  • background-size: cover
  • Sprites (of large images)
  • ‘Non-rendered’ content
  • Recalculating / Repainting the UI

Static images may render faster than CSS effects

Disney: "The Tortoise and The Hare"

Fonts

Fonts with Tall Ascenders Fonts with Tall Ascenders Fonts with Tall Ascenders Fonts with Tall Ascenders
Fonts: Zapfino, Helvetica, Savoye
Amount of space painted is large!

Large and Small Fonts

Open it!

Large and Small Fonts

www.fontsquirrel.com

Shadows

  • Not rendered as static bitmap
  • Evaluated each repaint
Render order: rendered from back to front

Text-indent

MyLogo Text
Logo
  • Use CSS Clip
  • Position text up instead of left

Large Gradients

    iphone with large gradient
  • Keep gradients small
  • Requires CPU to create
  • Stored in memory
  • Memory: Radial > Linear
  • Render Speed:
    Images often faster than Gradients

transitions

code {
   color: black;
   font-size: 85%;
   background-color: rgba(255,255,255,0.9);
   transition: all 2s ease-in 50ms;
}
code:hover {
   color: red;
   font-size: 120%;
   background-color: rgba(255,255,255,0.8);
}

Requires reflow!

transitions with transforms

code {
   color: black;
   font-size: 85%;
   background-color: rgba(255,255,255,0.9);
   transition: all 2s ease-in 50ms;
}
code:hover {
   color: red;
   transform: scale(1.4);
   transform-origin: 0 0;
   background-color: rgba(255,255,255,0.8);
}

Only repaints

Hardware Acceleration: 3d Transforms

 div {
  transform: translateZ(0);
 }

translateZ(0)

Composited mage in memory == H x W x 4

Take advantage of hardware acceleration, but don't abuse it. GPU accelerated elements eat video memory

Repaint

When visual changes do NOT require recalculation of layout

  • Visibility
  • Colors
  • Transforms
  • Background images
  • Transparency

Reflow

When visual changes REQUIRE recalculation of layout

  • Page load, Layout & orientation change
  • DOM Changes: Adding, removing, updating nodes
  • JS style information request
  • Changing value of display property
  • Changing to CSS property alters box model value
  • Resizing, zooming and scrolling (desktop), but not necessarily on mobile devices (viewport)
  • The larger a DOM tree, the more expensive a reflow is
  • Opera lists repaint and reflow as one of the 3 main contributors to sluggishness
  • Reflow of an element causes the subsequent reflow of all child and ancestor elements as well as any elements following it in the DOM.

Reflow

Minimize the DOM

  • Minimize number of nodes
    • Uses up memory
    • Measures each node for each repaint
  • Cache DOM lookups
    • Store them!
  • Minimize DOM manipulations
    • Batch DOM queries & DOM manipulations separately

More nodes = more expensive!

Reuse the DOM

Pool Elements and Objects

Reuse instead of Allocate and Destroy

tetris
  1. Create a pool of DOM elements (more than you need)
  2. Use the nodes you created
  3. Release back into pool
  4. Go to step 2

Responsive UI

Touch Events

  • Touch Event: 300ms delay
  • Extra touches aren't forgotten
  • co-opt with touch events with JS

Responsive UI

  1. Accept input
  2. Provide user feedback
  3. Update the UI

Tips

Test in Real Environments

iPhone showing which apps are running in the background
  • Test on Phone:
    • Simulator != Emulator
    • Cap your memory
  • Test with many apps open
  • Test on multiple devices
  • Test on mobile network

Tricks

  • Use tools
    • Even basic ones, like Activity Monitor
  • Scale down (not up)
  • Use average size fonts
  • Take advantage of HTML5 & native storage
  • Don't disable zoom (except for games)

Conclusion

  • Follow performance recommendations
  • Minimize Latency
  • Manage memory
  • Use CSS Judiciously
  • Use JS Minimally (and NOT for animation)
  • Batch query and manipulations separately
  • Reuse the DOM
  • Keep Mobile in Mind

Remember...

Your users may not be tethered

and their memory may be very limited.

Thank you

HTML5 and CSS3 for the Real World HTML5: The Definitive Guide MObile HTML5 Web Performance Daybook

Slides: estelle.github.com/mobileperf
Name: Estelle Weyl
Blog: standardista.com
Twitter: @estellevw

Who to follow