• Stars
    star
    242
  • Rank 167,048 (Top 4 %)
  • Language
  • Created over 9 years ago
  • Updated over 6 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Browser rendering optimization for 60fps smoothness!

Browser Rendering Optimization

Notes on browser rendering optimization and hitting 60fps smoothness!

Before understanding how to optimise web sites and applications for efficient rendering, itโ€™s important to understand what is actually going on in the browser between the code you write and the pixels being drawn to screen.

There are six different tasks a browser performs to accomplish all this:

  1. Downloading and parsing HTML, CSS and JavaScript
  2. Evaluating JavaScript
  3. Calculating styles for elements
  4. Laying out elements on the page
  5. Painting the actual pixels of elements

Sometimes you may hear the term "rasterize" used in conjunction with paint. This is because painting is actually two tasks: 1) creating a list of draw calls, and 2) filling in the pixels. The latter is called "rasterization" and so whenever you see paint records in DevTools, you should think of it as including rasterization.

Putting the user in the center of performance

  • 100 milliseconds
    • Respond to a user action within this time window and they will feel like the result is immediate. Any longer and that connection between action and reaction breaks.
  • 1 second
    • Within this window, things feel part of a natural and continuous progression of tasks. Beyond it, the user will lose focus on the task they were performing. For most users on the web, loading a page or changing views represents a task.
  • 16 milliseconds
    • Given a screen that is updating 60 times per second, this window represents the time to get a single frame to the screen (Professor Math says 1000 รท 60 = ~16). People are exceptionally good at tracking motion, and they dislike it when their expectation of motion isnโ€™t met, either through variable frame rates or periodic halting.

Browser rendering pipeline - 60fps

60fps = 16ms/frame, but you actually get only around 10-12ms to do all your work due to browser overhead.

App Life Cycles (RAIL)

  • Response
  • Animations
  • Idle
  • Load (XHR, Websockets, HTML imports etc.)

RAIL

Actual Chronological Order

  1. Load (~1 sec) Initial page load. Download and render your critical resources here.
  2. Idle (~ 50ms chunks) Do all non-essential work to ensure interactions that occur later on feel instantaneous. eg. lazy load items, do pre-animation calcs etc.
  3. Response (~100ms) On interaction, respond within 100ms.
  4. Animations (~16ms) In reality we get ~12ms since the browser has some overhead.

RAIL Time Table

What happens during style changes?

For example, during an opacity change or transform animation, only the composite is triggered.

  • The page isn't receiving any new HTML, so the DOM doesn't need to be built.
  • The page isn't receiving any new CSS, so the CSSOM doesn't need to be built.
  • The page isn't receiving any new HTML or CSS, so the Render Tree doesn't need to be touched.
  • If an opacity or transform changes affects element on its own layer, layout won't need to be run.
  • If an opacity or transform changes affects element on its own layer, paint won't need to be run.

For JavaScript code to run faster

  • Don't concentrate much on micro optimizations eg. for-loop vs while etc, since different JS engines (V8 etc.) handle it in different ways.
  • JS can trigger every part of the rendering pipeline(Style, layout, paint and compositing changes), hence run it as early as possible in each frame.

Animation

  • 'requestAnimationFrame' is the goto tool for creating animation.
    • Schedules the JavaScript to run at the earliest possible moment in each frame.
    • The browser can optimize concurrent animations together into a single reflow and repaint cycle, leading to higher fidelity animation. For example, JS-based animations synchronized with CSS transitions or SVG SMIL.
    • Plus, if youโ€™re running the animation loop in a tab thatโ€™s not visible, the browser wonโ€™t keep it running, which means less CPU, GPU, and memory usage, leading to much longer battery life.
  • Browser has to render frames at 60fps ie. 16ms/frame.
    • Due to browser overhead, we get around 10ms, so JS has about 3ms time.
  • JavaScript -> Style -> Layout -> Painting -> Composite
  • Do not use setTimout or setInterval for animations since JS engine does not pay attention to the rendering pipeline when executing this.
  • For IE9 - use 'requestAnimationFrame' with Polyfill.

Webworkers

  • Webworkers provide an interface for spawning scripts to run in the background - in a totally different scope than the main window and also in separate thread.
  • Webworkers and the main thread can communicate with each other.

Web Worker

Styles and Layout (Recalc Styles)

  • The cost of recalculate styles scales linearly with the number of elements on the page.
  • BEM: Block Element Modifier: Use this style for CSS selectors.
  • Class matching is often the fastest selector in modern browsers.
  • Reducing 'Recalculate Styles' time.
    • Reduce affected elements (fewer changes to render tree)
    • Reduce selector complexity (fewer tags & class names to select elements)
  • 'Forced synchronous layout' occurs when you ask the browser to run 'layout' first inside the JavaScript section and then do 'style' calcs and then layout is run again. Try to avoid it. Chrome dev tools (flame chart) helps to identify this.
  • Read layout properties and batch your style changes to avoid running layout as much as possible.
  • Layout thrashing happens when you do a 'forced synchronous layout' many times in succession.

Repaints and Reflows

Painting is the process by which the browser takes its abstract collection of elements with all their properties, and actually calculates the pixels to draw. This includes calculating styles such as box shadows and gradients, as well as resizing images. A repaint occurs when changes are made to an elements skin that changes visibility, but do not affect its layout. Examples of this include outline, visibility, or background color. According to Opera, repaint is expensive because the browser must verify the visibility of all other nodes in the DOM tree.

A reflow is even more critical to performance because it involves changes that affect the layout of a portion of the page (or the whole page). Reflow of an element causes the subsequent reflow of all child and ancestor elements as well as any elements following it in the DOM. According to Opera, most reflows essentially cause the page to be re-rendered.

So, if theyโ€™re so awful for performance, what causes a reflow?

Unfortunately, lots of things. Among them some which are particularly relevant when writing CSS:

  • Resizing the window.
  • Changing the font.
  • Adding or removing a stylesheet.
  • Content changes, such as a user typing text in an input box.
  • Activation of CSS pseudo classes such as :hover (in IE the activation of the pseudo class of a sibling)
  • Manipulating the class attribute.
  • A script manipulating the DOM.
  • Calculating offsetWidth and offsetHeight.
  • Setting a property of the style attribute

For the complete list check Paul Irish's gist

Compositing and Painting

  • Update Layer tree: Happens when Chrome's internal engine (Blink) figures out what layers are needed for the page. It looks at the styles of the elements and figures out what order everything should be in and how many layers it needs.
  • You can add independent elements of the page to it's own layer. However, adding a lot fo layers comes with a cost - so use it wherever it makes sense.
  • Adding layers using CSS:
    • Conventional way - supported in all browsers: transform: translatez(o);
    • New way - Chrome/Firefox support/No IE-Edge: will-change: transform;
  • Composite Layer: Is where the browser is putting the page together to center the screen.

Thanks to Paul Lewis and Cameron Pittman for their course on Udacity, which presented deeper insights to this topic.

Other Links:

Introducing RAIL: A User-Centric Model For Performance

The RAIL Performance model

More Repositories

1

react-bits

โœจ React patterns, techniques, tips and tricks โœจ
15,333
star
2

how-web-works

What happens behind the scenes when we type www.google.com in a browser?
15,083
star
3

js-bits

โœจ JavaScript concepts with code โœจ
JavaScript
2,822
star
4

css-refresher-notes

CSS Refresher!
1,546
star
5

web-security-basics

Web security concepts
1,152
star
6

async-javascript

Asynchronous Programming in JavaScript
JavaScript
388
star
7

react-es6-webpack-boilerplate

Lightweight boilerplate for React with ES6 (Babel) and Hot reloader using Webpack.
JavaScript
324
star
8

react-universal-starter

Quick start an Universal (isomorphic) React App
JavaScript
79
star
9

git-tips-and-tricks

Git Cheatsheet with Tips and Tricks
58
star
10

tic-tac-toe-js

A basic Tic Tac Toe game built using HTML/JavaScript/CSS
JavaScript
38
star
11

react-inline-edit

React Inline Edit is a component that allows inline/in-place edits.
JavaScript
37
star
12

node-deep-dive

Deep dive into Node.js and its workings
34
star
13

functional-js

Functional Programming in JavaScript
20
star
14

js-tricks

JavaScript tricks and tips
JavaScript
20
star
15

react-lite

A simple light-weight prototype of React
HTML
18
star
16

js-utils

JavaScript Exercises
JavaScript
15
star
17

leetcode-javascript

JavaScript
14
star
18

simple-promise-library

A simple implementation of a promise library
JavaScript
13
star
19

es6-examples

ES6 features and examples
JavaScript
12
star
20

react-16-upgrade

Notes on upgrading from React 15 to 16
9
star
21

algjs

JavaScript
7
star
22

redux-form-in-depth

Handling forms in redux!
JavaScript
7
star
23

my-resume

My updated resume
TeX
6
star
24

MirrorRoom-CSS-3D

A Mirror room created using CSS 3D Transforms.
JavaScript
6
star
25

react-redux-webpack

Getting started with React Redux and Webpack... Coming soon!
JavaScript
4
star
26

coding-puzzles

JavaScript
4
star
27

how-to-write-open-source-js

Code from Egghead.io course on How to "Write an Open Source JavaScript Library"
JavaScript
3
star
28

ui-bits

CSS
3
star
29

javascript-design-patterns

Repo of design Patterns in JavaScript
JavaScript
3
star
30

Skadoosh

Proof of concept website to host sessions virtually to share and learn skills with people across the globe.
HTML
3
star
31

react-loadable-example

Created with CodeSandbox
JavaScript
3
star
32

react-server-rendering

Info on React Server side rendering
3
star
33

Responsive-Tabs

A full width responsive tab component. The tab header uses icons for mobile view and text for larger width screens. I use three different layouts.
HTML
3
star
34

react-flux-router-app

Sample React-Flux app.. More details coming soon
JavaScript
2
star
35

react-banner-notification

Banner message/notification component
JavaScript
2
star
36

Scroll-Tracker

Scroll Tracker - A jQuery plugin that is used to track how far down the page users have seen.
JavaScript
2
star
37

Connect-Four-Game

Connect Four game using only HTML/CSS/Javascript
JavaScript
2
star
38

react-docs-code

Getting started with React
JavaScript
1
star
39

Flux-TodoMVC-Example

To demonstrate the Flux architecture with some example code, let's take on the classic TodoMVC application.
JavaScript
1
star
40

react-testing

Testing React Components
1
star
41

React-FEM-Exercises

React Exercises/Solutions from FrontEndMasters course online
JavaScript
1
star
42

reduxgram

Redux'ified Instagram
JavaScript
1
star
43

nodejs-google-api-integration

Google API integration with node.js (Currently Google Calendar API)
JavaScript
1
star
44

simple-polyfill-array-find-es6

Simple Polyfill for Array.find() in ES6
JavaScript
1
star
45

InView-jQuery-Plugin

Watch elements on the page and fire events when it is first viewed.
JavaScript
1
star
46

nodejs-push-notification-server

A simple push notification server built using nodejs
JavaScript
1
star
47

demo-chrome-extension

Simple Chrome Extension
JavaScript
1
star
48

react-complete-intro

Sample real-time React app that does streaming video
CSS
1
star