Improve Frontend, Animations & Scrolling Performance

Whether you’ve noticed it or not, website performance has become a hot topic in recent years. Most of the attention goes to loading time: how to make pages load faster by making files smaller, optimizing the server, and so on.

But what about performance after the page loads? In the past, there weren’t any suitable tools for analyzing Frontend Performance, and it wasn’t clear why anyone needed them.

In this article, I’ll show you how to find what makes scrolling and animations stutter on your site, and how to fix it.

This topic is broad and there’s a lot to say about it, so I’ll keep this guide focused on the most common causes of scroll and animation jank and how to fix them.

Why Scrolling Performance Matters

How people get online has changed drastically. A very large share of the population now browses the web on mobile devices. Mobile hardware has improved over the years, but mobile devices are still significantly less powerful than desktops and laptops. That means your site doesn’t perform as well on those devices, which can frustrate users or, worse, make them leave altogether.

As the sites I build get more complex, I need to make sure they’re still pleasant to use. Part of that means optimizing animations and scrolling performance (Scrolling Performance).

The usual goal is 60fps, which leaves the browser about 16.7ms to produce each frame. Many newer phones and laptops refresh at 120Hz, so on those screens the budget drops to about 8ms.

Hitting that target can be tricky on mobile devices, and sometimes even on laptops and desktops, especially on complex sites.

About Frontend Performance and the Repainting Action in Browsers

When you change the layout (where elements sit on the page), the browser has to redraw pixels on the screen. That’s called repainting.

Any change to an element’s attributes triggers a repaint, except a change to opacity or transform. When the browser changes the layout, it will always perform a repaint because any change to an element’s geometry means some pixels have to change.

In most cases, “arranging” the pixels on your screen is the most time-consuming action in the rendering pipeline and should be avoided as much as possible.

Every visual change goes through the same rendering pipeline: JavaScript, Style, Layout, Paint and Composite. Not every change needs all of them.

When only non-geometric attributes change, like backgrounds, text color, or shadows, the browser can skip the layout step. Changes to transform and opacity can skip paint as well. Try it:

What does the browser redo?

Pick a property. The box changes, and you can see which pipeline steps the browser has to run for it.

.box
Paint flashing
  1. JavaScriptchange a styleruns
  2. Stylewhich rules applyruns
  3. Layoutsizes and positionsruns
  4. Paintfill in the pixelsruns
  5. Compositestack the layersruns

Using Chrome Dev Tools to Identify Repainting Bottlenecks

Chrome Developer Tools makes it easy to spot which parts of your site the browser repaints. In the developer tools, open the Rendering tab and turn on “Paint flashing,” as shown below:

Paint Flashing option in Chrome Dev Tools Rendering tab

With that option on, Chrome flashes green over the areas it repaints. Scroll through your site and you’ll probably see several elements flash, even if it isn’t obvious why.

If you spot areas that keep flashing, take a closer look at what’s making the browser repaint them.

Here’s what that looked like when I scrolled through Savvy Blog. The video shows which areas the browser repainted before optimization. It doesn’t repaint those areas like this anymore.

Here’s what flashes green as I scroll:

  • The header at the top of the page.
  • The share buttons on the right.
  • The box with another article at the bottom left of the page.

The browser has to repaint all these parts every time someone scrolls. What do these three have in common? They all have position: fixed.

If scrolling stutters, the browser is probably doing a lot of repainting. The fixed elements I just pointed out can be a cause, as can various animations and similar effects.

I don’t want to change the site’s design just to get rid of those stutters, so here’s how to make scrolling smoother without doing that.

Creating new layers for certain elements can help avoid potential problems with scrolling and animation.

The idea is to reach a state where the site operates at 60FPS. The lower the frames per second, the higher the chance you will experience stutters in animations and scrolling.

Creating New Layers for Those Elements

The browser doesn’t have to treat everything on the screen as one image in memory.

Instead, you can give certain elements their own layers. Think of those layers as separate images the browser can handle independently of the other elements on the page.

Say an element uses position: fixed and shares a single layer with everything else on the page. When you scroll, the fixed element stays put while the other elements move relative to it. The browser has to repaint the whole layer each time.

Fortunately, the browser already knows how to optimize for this, though sometimes it needs a little help.

Giving certain elements their own layers means the browser doesn’t have to repaint everything each time. That’s what layer promotion means.

One layer or two?

A page with a fixed header scrolls on its own. Give the header its own layer and watch the green paint flashes stop.

Layer 1 · page
Layer 2 · header
Repaints while scrolling 0 1 layer: the header is painted into the page

A simplified model. Modern browsers promote many fixed elements on their own, so check your own page with Paint flashing before adding will-change.

The browser can repaint elements or move them with CSS transforms without affecting the other elements on the page. It’s a lot like Photoshop: you stack individual layers to make the final image.

The will-change Property

The best way to give an element its own layer is to use the CSS will-change property. The will-change property gives the browser a heads-up about what might change so it can optimize for that element before anything changes on screen.

All modern browsers support this property, and MDN lists it as available across browsers since January 2020. Give it the value transform, and the browser will create a new layer for that element.

.moving-element {
  will-change: transform;
}

One thing to watch for: will-change with certain values (like opacity or transform) creates a new stacking context. That can change how elements overlap. If z-index starts behaving differently after you add will-change, this is probably why.

Before will-change came along, developers used the translateZ(0) trick to force a layer. You’ll still see it in older code, but you rarely need it today:

.moving-element {
  transform: translateZ(0);
}

Before you reach for will-change, keep a few things in mind:

  • Don’t add will-change to too many elements. The browser already tries to optimize things on its own. Overusing this property can eat up memory and even slow down the page.
  • If you add the property in CSS, the browser keeps the optimization in memory much longer than it needs to. It’s better to use JavaScript to add the property just before the element changes and remove it once the change is done.
  • Don’t use will-change just because you suspect a performance problem. Save it for when you actually run into one, and use it only as a last resort.

Here’s what happened on Savvy Blog after I used will-change on the elements that were causing trouble:

All those green squares disappeared. Those elements got a new layer, so they no longer interfere with other elements on the screen.

How to Add will-change Using JavaScript

For this article, I added will-change in CSS on Savvy Blog. But as I mentioned, it’s better to use JavaScript to add the property just before the element changes and remove it afterward.

Here’s how I’d do that for a particular element:

var el = document.getElementById('element');

// Set will-change when the element is hovered
el.addEventListener('mouseenter', hintBrowser);
el.addEventListener('animationend', removeHint);

function hintBrowser() {
  // The optimizable properties that are going to change
  // in the animation's keyframes block
  this.style.willChange = 'transform, opacity';
}

function removeHint() {
  this.style.willChange = 'auto';
}

Event names are case-sensitive, so use animationend in lowercase. A listener for animationEnd never fires, so the hint would stay on the element forever.

The content-visibility Property

Another modern CSS property worth knowing about is content-visibility. Where will-change optimizes elements that animate, content-visibility: auto tells the browser it can skip layout and painting for elements that are entirely off-screen.

That’s especially useful on long pages with heavy content below the fold. The browser waits until the user scrolls to those sections before rendering them, which can dramatically reduce the initial rendering cost.

.below-the-fold-section {
  content-visibility: auto;
  contain-intrinsic-size: auto 500px;
}

With contain-intrinsic-size, you give the browser an estimated size for the element so it can calculate the scrollbar correctly before it renders the content. MDN lists content-visibility as Baseline 2024: it’s worked in all current major browsers since September 2024.

There’s a limit, though. It saves the browser some rendering work on content it hasn’t reached yet. It won’t do anything for a busy section that’s already on screen, like one with an animation running.

JavaScript Animation Loops That Cause Jank

Paint flashing shows you what the browser repaints, but some of the worst scroll jank comes from JavaScript running every frame. A loop that takes 6ms per frame on your laptop can easily take 25ms on a mid-range phone. At that point, the page misses frames every time you scroll.

I ran into exactly this on the new Savvy homepage and fixed it. Here’s what I found, in order of impact.

Avoid Layout Thrashing (Read First, Then Write)

If you change a style and then read a layout value like offsetWidth or getBoundingClientRect(), the browser has to recalculate styles, and layout if needed, right then to give you the right answer. That’s a forced synchronous layout, also called a forced reflow. Do it in a loop and you get layout thrashing.

The rule from web.dev is simple: batch your reads first, then do your writes.

// Bad: write, then read, on every item, every frame
items.forEach(function (el) {
  el.style.transform = 'translateX(' + x + 'px)';
  var w = el.offsetWidth; // forces a synchronous style/layout pass
});

// Good: read everything first (or cache it), then write
var widths = items.map(function (el) { return el.offsetWidth; });
items.forEach(function (el, i) {
  el.style.transform = 'translateX(' + (x - widths[i] / 2) + 'px)';
});

Better yet, cache the values that rarely change. A label’s width only changes when its text changes, so measure it then, not on every frame.

Stop Animation Loops You Can’t See

Browsers pause requestAnimationFrame in background tabs, but not when an element scrolls out of view. That canvas animation in the hero keeps running while someone reads the footer, unless you stop it.

With IntersectionObserver, you can run the loop only while the element is visible:

var raf = 0, visible = false;

function frame(now) {
  draw(now);
  raf = visible ? requestAnimationFrame(frame) : 0;
}

new IntersectionObserver(function (entries) {
  visible = entries[0].isIntersecting;
  if (visible && !raf) raf = requestAnimationFrame(frame);
}).observe(document.querySelector('.hero'));

The key is that the loop actually stops. It’s easy to check a “paused” flag and still call requestAnimationFrame again. That just keeps waking up the main thread for no reason.

This works for CSS animations, too. When a section leaves the viewport, toggle animation-play-state: paused on it.

Skip Style Writes That Don’t Change Anything

Animation code often writes the same inline style on every frame, even if the value hasn’t changed. Each write can trigger a style recalculation, and if color or background changes, that also triggers a repaint.

Keep track of the last value you wrote and check it before writing again:

var last = '';

function setTransform(el, value) {
  if (value === last) return;
  el.style.transform = value;
  last = value;
}

If a value triggers a repaint, like a color as it fades in, round it to a few dozen steps. Your eye won’t notice the difference, and you can skip the write entirely on most frames.

Canvas: Batch Draw Calls and Cap the Pixel Ratio

When you use an HTML canvas for a background effect, two things matter most.

Start by batching your draw calls. If you’re drawing 1,000 dots, making 1,000 separate fill() calls is far slower than grouping dots of the same color into one path. MDN’s canvas optimization guide recommends batching calls and avoiding unnecessary state changes.

var paths = {}; // one Path2D per color

dots.forEach(function (d) {
  var p = paths[d.color] || (paths[d.color] = new Path2D());
  p.moveTo(d.x + d.r, d.y);
  p.arc(d.x, d.y, d.r, 0, Math.PI * 2);
});

for (var color in paths) {
  ctx.fillStyle = color;
  ctx.fill(paths[color]);
}

Second, keep an eye on the pixel ratio. On a Retina screen, a canvas scaled by devicePixelRatio holds four times as many pixels. The browser has to clear, draw and upload every one of them on every frame. For soft, decorative effects, I cap the ratio at 1.5. It looks the same and saves the browser a lot of work.

Use Passive Listeners, or No Scroll Listener at All

A scroll, wheel or touchmove listener can delay scrolling while the browser waits to see if you call preventDefault(). Marking it passive tells the browser it can scroll right away.

window.addEventListener('scroll', onScroll, { passive: true });

Better yet, do you need a scroll listener at all? If you’re just asking, “Is this element on screen?” use IntersectionObserver. You can often handle scroll-linked effects in CSS. If you do need a scroll handler, use requestAnimationFrame to schedule the work rather than running it on every event.

How to Measure Scrolling Performance

Almost any page scrolls smoothly on a fast development machine. Slow yours down before you measure so you can see what your visitors see.

  • Open the capture settings in the Chrome DevTools Performance panel and set CPU throttling to 4x slowdown.
  • Test at a device pixel ratio of 2. Most phones and many laptops have high-density screens, so there are more pixels to deal with. That drives up canvas and paint costs.
  • Start a recording and scroll through the whole page. Then look for long tasks, and for purple Recalculate style or Layout events nested inside your own JavaScript. Those are forced reflows.
  • In the Rendering tab, turn on “Frame rendering stats” so you can see dropped frames as you scroll.

Here’s a recording of the old code for the client logos band on the Savvy homepage at 4x CPU slowdown. At the end of every frame, there’s a small purple Recalculate style box under the animation’s place() function. That function read offsetWidth right after writing styles. The Forced reflow insight in the sidebar explains why that matters.

Chrome DevTools Performance panel showing a forced Recalculate style event inside the place() animation function, with the Forced reflow insight

The detail to notice here is that the browser had to recalculate styles, not redo the layout. The loop only changed transform, opacity and color, so the layout was still valid. The browser still had to compute styles synchronously on every frame.

With Frame rendering stats, you can watch this happen live. According to Chrome’s documentation, blue lines mean frames rendered successfully, yellow lines mean they were partially presented, and red lines mean they were dropped. Here’s the same page at 20x slowdown:

Chrome Frame rendering stats overlay with a frame bar full of red dropped frames and yellow partially presented frames

You’re looking for a bar that stays mostly blue as you scroll. If you see a lot of red, the main thread or the GPU can’t keep up.

Change one thing at a time and measure before and after each change. On the Savvy homepage, my fixes above cut the JavaScript time for a full scroll from about 250ms to about 140ms (4x CPU throttle, 2x pixel ratio). I also tried adding content-visibility to the same page, but it made no measurable difference, so I left it out.

The fastest way to waste time on performance is to apply every tip you have read. Measure, find the one thing that costs the most, fix it, and measure again.

Tips for Better Frontend Performance

A few changes can make scrolling and animations run better on your site. That takes some work off the CPU/GPU, makes for happier visitors, and uses less battery power on mobile devices.

  • Avoid using background-attachment: fixed on background images. In some browsers, it makes the browser repaint as you scroll, which hurts performance.
  • If a slider or animation on your site lights up in Paint flashing, use the will-change CSS property to give it its own layer.
  • If your site uses lots of CSS effects, like rounded corners, linear-gradient values and shadows, consider cutting back. These effects are fine on their own, but too many will hurt frontend performance.
  • Always use the exact image size the browser needs to display. If you work with WordPress, take a look at the guide I wrote about creating image sizes for WordPress sites.
  • For JavaScript-driven animations, use requestAnimationFrame to stay in sync with the browser’s refresh cycle. That way, your animation code runs at the right time and avoids unnecessary frame drops.
  • Whenever possible, animate only transform and opacity. They’re the only properties the browser’s compositor thread can handle without triggering layout or paint. Animating properties like width, height, top, or left costs significantly more.

FAQs

A few common questions about frontend performance and scrolling optimization:

What causes janky scrolling on websites?
Janky scrolling is typically caused by heavy repainting. Elements with position: fixed, complex CSS effects, large background images with background-attachment: fixed, and JavaScript-heavy scroll handlers can all trigger expensive repaints that drop the frame rate below 60fps.
What is layer promotion and when should I use it?
Layer promotion means moving an element to its own compositor layer so that it can be painted and animated independently from the rest of the page. Use it when a position: fixed element or a frequently animated element causes visible repaints. The easiest way is to apply will-change: transform to that element.
Can I add will-change to every element on my page?
No. Adding will-change to too many elements is counterproductive. Each promoted layer consumes GPU memory, and the overhead of managing many layers can actually make performance worse. Only apply it to elements that are causing measurable performance issues.
What is the difference between will-change: transform and transform: translateZ(0)?
Both promote an element to its own layer. transform: translateZ(0) is an older hack that forces a 3D transform context. will-change: transform is the standards-based approach that signals intent to the browser without actually applying a transform. Use will-change in modern browsers and fall back to translateZ(0) only if you need to support very old browsers.
Which CSS properties are cheapest to animate?
The cheapest properties to animate are transform and opacity. These can be composited on the GPU without triggering layout or paint. Animating any other property, such as width, height, top, left, or margin, triggers layout recalculations, which are significantly more expensive.
How does content-visibility: auto help with performance?
The content-visibility: auto property tells the browser to skip rendering (layout and paint) for elements that are off-screen. This can dramatically reduce the initial rendering cost of long pages. The browser will render those sections only when the user scrolls to them.
Why does my page still stutter after I added will-change?
Layers fix repaints, not JavaScript. If a requestAnimationFrame loop writes styles and then reads layout values like offsetWidth, it forces a style or layout recalculation on every frame. Loops that keep running off screen and canvas effects drawn at full pixel ratio are other common causes. Record a scroll in the DevTools Performance panel to find which one it is.
How do I test scrolling performance on a fast computer?
Set CPU throttling to 4x slowdown in the Chrome DevTools Performance panel and test at a device pixel ratio of 2. Then record a full scroll and turn on "Frame rendering stats" in the Rendering tab to see dropped frames.

Summary

Chrome’s developer tools give you plenty of ways to spot performance issues on your site and figure out what’s behind them, whether you’re looking at Frontend performance or loading time performance.

If animations or scrolling are giving you trouble, creating a separate layer for certain elements is the right move. The will-change property works well for this, especially on complex sites. Use it where you need it, but don’t overdo it.

Layers are only half the story, though. In my experience, JavaScript animation loops can cause just as much jank. That includes layout thrashing, loops that keep running off screen, and heavy canvas effects. I wrote about a related case where hero animations were hurting my LCP.

For broader CSS performance optimization, it’s worth going through your stylesheets to look for expensive properties and effects that go a bit too far.

And while we’re on the subject of scrolling, I also wrote about CSS driven scroll animations using AOS.

Summarize with AI Claude ChatGPT Google AI
Discussion
[  0 Comments  ]

Leave a Comment

To add code, use the buttons below. For instance, click the PHP button to insert PHP code within the shortcode. If you notice any typos, please let us know!