requestAnimationFrame Web Api

Browser

About

requestAnimationFrame is a window function that permits to run code when a frame is going to be painted.

Usage

Avoiding layout shift

Avoiding layout shift.

For instance, when you create a fixed top bar, you need to set two layout properties that will move down and up element. To avoid moving the elements independently , you can run the code in a requestAnimationFrame callback.

Example with a dynamic correction of a fixed top header such as the Bootstrap navbar where:

  • we add the fixed-top class that set the position to fixed
  • and correct it with a padding on the body.
window.requestAnimationFrame(function() {
    let fixedNavbar = document.querySelector(".navbar[data-type=\"fixed-top\"]")
    fixedNavbar.classList.add("fixed-top");
    let offsetHeight = fixedNavbar.offsetHeight;
    document.body.style.setProperty("padding-top",offsetHeight+"px");
});

Simulating the First rendering event

There is no rendering page load event that notify of the first rendering but as the rendering complete after the first two animation frames rendering of the window load event, you can simulate the event with the requestAnimationFrame web api function.

Example:

function renderingCompleted() {
        console.log("Rendering completed")
}
function renderingStarted() {
    console.log("Rendering started");
    requestAnimationFrame(renderingCompleted);
}
window.addEventListener("load", function () {
    requestAnimationFrame(renderingStarted);
});
  • Output:

Slow the call rate of function (Debounce)

debounce function permits to limit the execution rate of callback function.

The below example shows the use of the requestAnimationFrame that executes its own callback function either to:

Example to limit the scroll event.

document.addEventListener('scroll', function(e) {

  if (!ticking) {
    window.requestAnimationFrame(function() {
      // intensive operation
      ticking = false;
    });

    ticking = true;
  }
});

Frame Timeline

To get a feeling on when your code is going to run, you can see the frame timeline in the Chrome Devtool Performance Tab

Devtool Chrome Performance Frames





Discover More
Layout Shift Devtool Performance
Layout Shift: How to prevent it ? (Cumulative Layout Shit / CLS)

A layout shift occurs when the rendering of the web page shifts / move element from their current position. For instance: without the knowledge of the target ratio (via the height and width attribute...
Page Loading Key Moment
Web - Timeline of a page load (Page Speed|Page Latency)

Page load is the latency performance metrics that cumulates: TCP latency (ie how fast, the network will receive the HTTP request and send back the HTTP response ) HTTP latency (ie how fast the web...



Share this page:
Follow us:
Task Runner