Table of Contents

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