Tips, Tricks & Hacks

in the pursuit of

Speed

Neil Jenkins / @neilj

FastMail

Part II:
The DOM Strikes Back

How Browsers Work

(from 30,000ft)

  • Document Object Model
  • CSSOM: CSS Object Model
  • Render Tree

What is layout/reflow?

  • Walks the render tree
  • Resolves constraints
  • Calculates dimensions
  • This is expensive

What is repaint?

  • Walks the render tree
  • Updates bitmap where dirty
  • Not quite as expensive

What is recomposite?

  • Layers (subtrees) drawn separately
  • Composited in GPU
  • Simple manipulation of layers
  • Fast! (Given a reasonable GPU)

Generating the DOM

  1. Strings -> `innerHTML`
  2. `document.createElement`

Performance comparison

Sugared DOM

var items = [ 1, 2, 3, 4 ];
el( 'div#message', [
    el( 'a.biglink', { href: 'http://www.google.com' }, [
        'A link to Google'
    ]),
    el( 'ul', [
        items.forEach( function( item ) {
            return el( 'li.item', [ item + '. Item ] );
        })
    ]),
    items.length > 1 ? 'There are lots of items'.localise() + '. ' : null,
    'This is just plain text. <script>I have no effect</script>'
])

Other benefits

  • Easy to debug
  • Less code
  • No DOM querying
  • No XSS
  • No extra white-space nodes
  • Full power of JS

Updating the DOM

  1. Update model
  2. Propagate change (bindings)
  3. Update DOM
  4. Reflow/redraw/recomposite
  5. Measure rendered objects

Animation on mobile

  • Animation must only recomposite.
  • Transform/opacity
  • (Colour = redraw, can be OK)
  • WebKit: `translate3d(...)`

Hack: Including conflicting content

  • CSS could conflict with page.
  • <iframe>s are slow
  • Solution: 1 iframe, examine the CSSOM, use querySelector to apply to nodes in original document.

Thank You