Skip to content

Optimizing Browser Performance

Mithi Sevilla edited this page Apr 4, 2021 · 1 revision

Optimizing Browser Performance

Performance Metrics Definitions

  1. Time to first byte - time from issuance of http request until the web browser receives the first byte of the response
  2. Page load time- time since issuance of HTTP request until the page has finished loading completely

Parsing and Page Rendering

Components of a browser

  1. User Interface - interactive elements like buttons, except for the window where the page is displayed
  2. Browser engine - go-between for UI and rendering engine
  3. Rendering engine - Renders the requested content
  4. Networking - Handles network calls, http requests
  5. UI backend - used to draw basic widgets like list boxes, windows, exposes generic interface that uses operating system methods underneath
  6. Javascript engine Parses and executes javascript code
  7. data storage - persists memory to store information like cookies, password and history

Refresh rates

  • Most browsers refresh 60 frames per second, so each frame has a budget of 16.66 ms, if you fail to meet this, the frame rate drops and the content judders on screen (referred to as jank)

Rendering engines

  • displays whatever information was requested (html, xml, images by default) plugins can render PDFs etc

FIRST: HTML parsing + dom Rendering engine receives HTML file, it parses it into a parse tree, converting it to a tree called th DOM which is the object representation of the HTML document. It is created before scripts or external factors make any changes to it

SECOND: render tree construction and style calculations frame tree or render tree is created by traversing the DOM nodes and calculating css style values for each node. Styling information and html together are used to create the render tree. Style information for each node. Calculated from the DOM tree.

THIRD: Layout Exact coordinates of each element that each node represents are calculated (the layout). Size and placing of elements affect the rest, and the size of the children of all the elements depend of their respective parent elements. Quite a lot of calculations.

FOURTH: Painting

  • Convert to actual pixels on the screen.
  • Create a list of draw calls, then fill in the pixels ("rasterizing")
  • Done in different threads and typically done in multiple surfaces (layers)

FIFTH: Compositing

  • Multiply layers of drawing must be drawing on the screen in the correct order, some elements overlap, takes advantage of the GPU

The pipeline

javascript
|
Style calculations (always happens!)
|
layout
|
paint
| 
compositing

If you go to a website and the connection drops before rendering you can already expect to see something because the browser starts to parse and display whatever it receives as soon as it can. So if the browser receives part of the root HTML file, it will start displaying it.

When you visit and a pop-up form asks you to sign up for their newsletter and everything else gets covered with translucent grey overlay, the part of the rendering process that was triggered is compositing because nothing had to be restyled of layout because the newsletter form is just another layer added.

When you visit a website and the colors of a circle keep changing for effect, nothing else changes, painting definitely occurs

Rendering Performance

Three ways the pipeline normally plays out

JS > Style > Layout > Paint > Composite If you change the element's geometry like width or position, the browser has to check all the other elements (reflow) and all affected areas need to be repainted. Avoid expensive browser reflows

JS/CSS > Style > Paint > Composite If you change paint only property like background image, text color or shadows, then the browser skips layout

JS/CSS > Style > Composite This is the cheapest. This is animations, scrolling or web pop up. A layer is added but no positions or colors of any element changes

Developer tools

Create an example app Make images randomly move across the screen. Have a few buttons. Buttons to decrease or increase number of images. Stop or start the animations.

** Record performance data** Go to performance, tab and click record, do something (like click a button) then stop recording. View results

** Analyze performance data** FPS Chart

  • When there is a red bar above the "FPS", then it means the frame rate dropped so low. The higher the green bar the higher the FPS.

CPU panel

  • Colors of CPU chart correspond to the colors of the summary tab at the bottom of the performance panel. If it is in full color then the CPU was maxed out during recording. When you see CPU maxed out for long periods, it's a cue to find ways to do less work.

Hovering

  • When you hover the panels it shows a screenshot of the app at a point in time.

Clicking / scrubbing

  • to manually analyze the progression of animation

Frames panel

  • when you hover at a particular frame it will show you the FPS at that frame

MAIN SECTION You can see the timeline with bar for each event like for example for 0 - 500ms the animation frame fired from 500 - 700 ms update layer three and from 700 - 750 ms, we do painting. Wider events are longer. X axis recording over time, Y axis represents the call stack. Events are stacked on top of each other. Upper events caused the lower events. The red triangle on the bar means that there may be an issue related to the event and you might want to investigate and optimize this.

When you click an event (like animation frame fired) it shows you information about that event like total time , warning: recurring handle took 66.63ms and a link to index.js:95 which when you clink on it jumps you to the relevant line in the source code. Under the app.update which is under animation frame fired and then function call there is a bunch of purple events. They have a red triangle on their upper right corner so it's taking really long that it affects the user experience.

Frame rate is a common measure of website performance.

Optimize Javascript Animation

requestAnimationFrame

  • has less CPU consumption, animations in inactive tabs stop, saves battery. setTimeout() or setInterval() to do visual changes like animation, but this callback will run at some point in the frame and can often have the effect of causing us to miss a frame resulting in jank.

Promoting elements to the GPU

  • CSS animations don't affect document flow which means it can offload them off to the GPU. transforms like scale, rotation, translation, skew and opacity get offloaded to the GPU

Improving scrolling performance

Reduce complexity or use web workers

Javascript runs on the browser's main thread, with style calculations, layout, and sometimes paint. If JS runs for a long time, it will block these other tasks. If you're in an animation like scrolling, the javascript must be in the region of 3-4ms if not in may block scrolling

You can move pure computational work to WEBWORKERS, works that don't require DOM access like data manipulation or traversal such as sorting or searching and also loading and model generation. Web workers don't have dom access.

Batch larger tasks to micro-tasks

Reducing browser reflows

Some things that cause reflow

  • window resizing
  • changing the font of an element
  • making changes to content itself
  • adding or removing style sheet or css classes
  • modifying or calculating size
  • changing position
  • calculating position
  • changing orientation
  • dom manipulation

tricks to avoid reflow

  • Reduce unnecessary DOM depth. Change at one level of the DOM tree can cause changes at every level of the tree all the way up to the - root and all the way down to the children of the modified node
  • class changes should be done at the lowest level of the dom tree
  • batch DOM manipulation, a lot of front end frameworks provide this very advantage
  • Use position-absolute or position-fixed to accomplish complex rendering changes
  • minimize CSS rules and remove unused CSS rules, avoid complex css selectors, try not to modify inline to much
  • promote elements to the GPU

Content Optimizations

  • Minifying - remove unnecessary spaces, line indents, code
  • gzip - to reduce file sizes
  • reduce image sizes
  • reduce number of plugins
  • JPEG and SVG has metadata that can be removed to compress files

Communication with the GPU takes some overhead. Not all style changes in javascript causes a reflow. Promoting elements to the GPU does not always lead to better animation performance. Not all CSS animations get promoted to GPU.