Done in 0.0166666666 seconds

I'm Alex, nice to meet you!

@alexnmoldovan

Co-Founder @JSHeroes

   freecodecamp.org/news/author/alexnm/

No Servus 🇷🇴Timișoara!

Open Source Engineer @teleportHQ

http://bit.ly/revojs-alex

"We will build sites that perform badly"

"We shouldn't be afraid of getting our hands dirty"

Browser Rendering Pipeline

JavaScript

Style Calc

Layout

Paint

Composite

1 second = 60 frames

1/60 = 0.0166666666s

= 16 ms for rendering

16 ms

16 ms

16 ms

16 ms

10ms

10ms

10ms

10ms

In an ideal world...

javascript logic

business logic

event handlers

data fetching

dom diffing

data processing

...

16 ms

16 ms

16 ms

16 ms

10ms

40ms

In the real world...

Audit Time!

1. DOM Access

Multiple DOM accesses

for (let index = 0; index < newsItems.length; index++) {
    const newsBox = document.createElement('div')

    /* ... */

    const newsItemsList = document.getElementById('news-items-list')
    newsItemsList.appendChild(newsBox)
}

Involuntarily Layout Trigger

const header = document.getElementById('header')

function handleScroll() {
    if (window.scrollY > 50) {
        header.style.position = "fixed"
    }
}

Forced Synchronous Layout = FSL

FSL = Layout Trashing

const header = document.getElementById('header')

function handleScroll() {
    if (window.scrollY > 50) {
        header.style.position = "fixed"
    }
}

1. DOM Access

2. JavaScript

Avoid Long Running Handlers

Event Throttling

Passive Event Listeners

addEventListener('touchstart', onTouchStart, {passive: true});

1. DOM Access

2. JavaScript

3. Animations

JavaScript Animations

function animateBox() {
    /* ... */
    offset = offset + step
    box.style.marginLeft = offset + "px";
    /* ... */
    requestAnimationFrame(animateBox);
}

Style

Layout

Paint

Composite

Style

Layout

Paint

Composite

Style

Layout

Paint

Composite

CSS Animations

Layout

Paint

Composite

Paint

Composite

Composite

Does it change the geometry of the element?

(ex: width, margin, border)

Is it a visual property?

(ex: color, background-color, visibility)

Does it promote the element to a new layer?

(ex: transform, opacity)

will-change

Use it as a last resort

Don't over use it, composition is not cheap

Test how the browser optimizes the layers before using it

Recap

Avoid unnecessary or repetitive DOM access

Use requestAnimationFrame for all visual delays / animations

Throttle sensitive event handlers (ex: scroll, resize)

Use passive event listeners for an easy win

Avoid forced reflows / layout trashing

Prefer transform and opacity for css animations

Use will-change as a last resort to promote an element to its own layer

Resources

I'm open for questions!

@alexnmoldovan

Co-Founder @JSHeroes

   freecodecamp.org/news/author/alexnm/

Mulțam fain 🇷🇴Timișoara!

Open Source Engineer @teleportHQ

http://bit.ly/revojs-alex

Ciao ciao!

Made with Slides.com