Home > Web Front-end > JS Tutorial > 7 Performance Tips for Jank-free JavaScript Animations

7 Performance Tips for Jank-free JavaScript Animations

Jennifer Aniston
Release: 2025-02-15 09:13:12
Original
605 people have browsed it

7 Performance Tips for Jank-free JavaScript Animations

Key Points

  • To obtain better animation performance and avoid animation of CSS properties that trigger posting or drawing operations, use properties that have been optimized by modern browsers, such as transform and opacity.
  • The elements to be animated can be promoted to their own layers using the CSS will-change attribute, but this should be done with caution, as it requires memory and management.
  • Replace requestAnimationFrame with setTimeout/setInterval to reduce the risk of lag and ensure smoother animations, as this method executes animation code at the best time for the browser.
  • For complex drawing operations in HTML5 Canvas, use off-screen canvas to improve performance by performing all drawing operations on the off-screen canvas and then drawing off-screen canvas on each frame.

The role of web animation has evolved from simple decorative effects to specific roles in the user experience—for example, providing visual feedback as users interact with your application, guiding users to focus to achieve the application’s goals, Provide visual tips to help users understand the application interface, etc.

To ensure that web animations are competent for these critical tasks, it is important that the movement must be performed smoothly at the right time so that users can see it as aid rather than anything that hinders them from trying to perform on the application.

Bad animation design can lead to an annoying effect - jank, which is explained by jankfree.org:

Modern browsers try to refresh content on the screen synchronously with the refresh rate of the device. For most devices today, the screen refreshes 60 times per second, or 60Hz. If there is some movement on the screen (such as scrolling, transitions, or animation), the browser should create 60 frames per second to match the refresh rate. A stutter is any stutter, jitter, or simple pause that a user sees when a website or application fails to keep up with the refresh rate.

If the animation is stuck, users will eventually interact with your application less and less, which will negatively affect its success. Obviously, no one wants that.

In this article, I have collected some performance tips to help you solve JavaScript animation problems and more easily achieve 60fps (frames per second) goals, enabling smooth motion on the network.

1. Avoid animation of costly CSS properties

Whether you plan to use CSS transition/CSS keyframes or JavaScript to animate CSS properties, understand which properties cause page geometry to change (layout) - which means that the location of other elements on the page must be recalculated , or it will involve drawing operations - this is very important. Layout and drawing tasks are very expensive to handle for browsers, especially when there are multiple elements on the page. So if you avoid animating CSS properties that trigger posting or drawing operations and stick with properties like transform and opacity, you'll see a significant improvement in animation performance, as modern browsers are optimizing These attributes are done very well.

On CSS Triggers, you can find a latest list of CSS properties that contain information about the actions they trigger in each modern browser, including the first and subsequent changes.

7 Performance Tips for Jank-free JavaScript Animations

Changing the CSS properties that trigger only synthesis operations is a simple and effective step you can take to optimize web animation performance.

2. Raise the elements to be animated to their own layers (make careful)

If the element to be animated is on its own synthesizer layer, some modern browsers will use hardware acceleration to offload work to the GPU. If used properly, this can have a positive impact on the performance of the animation.

To make an element sit on its own layer, you need to upgrade it. One way is to use the CSS will-change property. This property allows developers to warn the browser in advance that they want to make some changes to the element so that the browser can make necessary optimizations in advance.

However, it is not recommended that you lift too many elements onto their own layers, or do so inflatedly. In fact, every layer created by a browser requires memory and management, which can be expensive.

You can learn more about how to use will-change, its advantages and disadvantages in Nick Salloum's Introduction to CSS will-change Attributes.

3. Use requestAnimationFrame Replace setTimeout/setInterval

JavaScript animations are usually encoded using

or setInterval(). setTimeout()

The code is as follows:

var timer;
function animateElement() {
  timer = setInterval(function() {
    // 动画代码在此处
  }, 2000);
}

// 要停止动画,请使用 clearInterval
function stopAnimation() {
  clearInterval(timer);
}
Copy after login
Copy after login
While this works, the risk of lag is high, because the callback function runs at some point in the frame, which may at the end, which can lead to one or more frames missing. Today, you can use a native JavaScript method designed for smooth web animations (DOM animations, canvases, etc.), called

. requestAnimationFrame()

Execute your animation code at the best time for the browser, usually at the beginning of the frame. requestAnimationFrame()

Your code might look like this:

var timer;
function animateElement() {
  timer = setInterval(function() {
    // 动画代码在此处
  }, 2000);
}

// 要停止动画,请使用 clearInterval
function stopAnimation() {
  clearInterval(timer);
}
Copy after login
Copy after login

Tim Evko's "Update Performance with RequestAnimationFrame" on SitePoint provides a great video introduction about encoding using requestAnimationFrame().

4. Decouple events from animation in code

With 60 frames per second, the browser only has 16.67ms per frame to do its job. There is not much time, so keeping your code streamlined may have an impact on the fluency of your animation.

Decoupling code that handles scrolling, resizing, mouse events and other events from the code that uses requestAnimationFrame() to handle screen updates is a good way to optimize the performance of animation code.

For an in-depth discussion of this optimization tip and related sample code, check out Paul Lewis' Create leaner, more powerful, and faster animations with requestAnimationFrame.

5. Avoid long-running JavaScript code

The browser uses the main thread to run JavaScript, as well as other tasks such as style calculations, layouts, and drawing operations. Long-running JavaScript code can negatively affect these tasks, which can cause frames to be skipped and cause animation stuttering. So simplifying your code is definitely a great way to ensure that your animations run smoothly.

For complex JavaScript operations that do not require access to the DOM, consider using Web Workers. A worker thread performs its tasks without affecting the user interface.

6. Use browser developer tools to control performance issues

The browser's developer tools provide a way to monitor the difficulty of the browser running your JavaScript code or third-party libraries. They also provide practical information about frame rates and more.

You can access Chrome DevTools by right-clicking on the web page and selecting Check in the context menu. For example, using performance tools to record your web page will give you an in-depth understanding of the performance bottlenecks on that page:

7 Performance Tips for Jank-free JavaScript Animations

Click the "Record" button and stop recording after a few seconds:

7 Performance Tips for Jank-free JavaScript Animations

At this point, you should have a lot of data to help you analyze the performance of your page:

7 Performance Tips for Jank-free JavaScript Animations

This Chrome DevTools guide will help you make the most of DevTools to analyze performance and many other types of data in your Chrome browser. If Chrome isn't your browser of choice, that's OK, because most modern browsers today come with powerful DevTools that you can use to optimize your code.

7. For complex drawing operations, use off-screen canvas

This technique is specifically related to optimizing HTML5 Canvas code.

If your frame involves complex drawing operations, a good idea is to do all drawing operations once or only once when changes occur, and then draw only the off-screen canvas on each frame.

You can find detailed information and code examples and more about this tip in MDN's Optimization Canvas article.

Conclusion

Optimizing code performance is a necessary task if you don't want to live up to users' expectations on today's network, but it's by no means easy. There may be several reasons for your poor animation performance, but if you try to use the tips listed above, you will take a big step towards avoiding the most common animation performance traps, improving the user experience of your website or app .

FAQs (FAQ) on JavaScript animations without lags

What is the concept of "stuttering" in JavaScript animation?

"Stutter" refers to any stutter, jitter, or simple pause that a user sees when a website or application fails to keep up with the refresh rate. In JavaScript animations, lags may occur when the frame rate is below the standard 60 frames per second. This can result in less smooth animation and less visually engaging, which can negatively affect the user experience.

How to ensure smooth JavaScript animations?

Making JavaScript animation smooth involves optimizing the code to maintain a stable 60 frames per second. This can be achieved by using the requestAnimationFrame method, which allows the browser to optimize animations. You can also use CSS transitions or animations for simple animations, as they are generally more efficient than JavaScript. Additionally, layout jitter is avoided by batching the DOM read and write operations together.

requestAnimationFrame What is its role in JavaScript animation?

The requestAnimationFrame method in JavaScript is a key tool for creating smooth animations. It tells the browser that you want the animation to be executed and asks the browser to call the specified function to update the animation before the next repaint. This method allows the browser to optimize animations, resulting in smoother and more efficient animations.

Why may CSS transitions or animations be more efficient than JavaScript?

CSS transitions and animations may be more efficient than JavaScript because they are processed by the browser's synthesizer thread and are separated from the main JavaScript thread. This means that even if the main thread is busy with other tasks, they can run smoothly. Additionally, certain properties can be animated in CSS without causing redrawing, which makes them particularly efficient.

What is layout jitter and how to avoid it in JavaScript animations?

Layout jitter refers to JavaScript repeatedly reading and writing to the DOM, causing the browser to recalculate the layout multiple times, resulting in inefficient and stuttering animations. This can be avoided by batching DOM read and write operations together. For example, you can do all the reads and then all the writes instead of interleaved reads and writes.

How to use will-change Attribute optimization JavaScript animation?

The

property in CSS allows you to inform the browser in advance what types of changes you might want to make to the element so that it can set appropriate optimizations before it needs to. This can significantly improve the performance of the animation. However, use it with caution, as overuse can cause the browser to spend too much time optimizing. will-change What does the

and transform properties mean in JavaScript animations? opacity The

and

properties in transformCSS are particularly efficient for animations. This is because changes to these properties can be handled by the browser's synthesizer thread without layout or drawing. This means that they can run smoothly even if the main JavaScript threads are busy. opacity

How to use Web Workers to improve the performance of JavaScript animations?

Web Workers in JavaScript allow you to run scripts in the background, separate from the main execution thread. This means they can handle compute-intensive tasks without blocking the main thread and causing lag. However, they have some limitations, such as inability to access the DOM or some Web APIs.

What is "non-main thread" animation and how does it benefit JavaScript animation?

"Non-main thread" animation refers to running an animation on a separate thread separate from the main JavaScript thread. This can significantly improve the performance of the animations, as it allows them to run smoothly even when the main thread is busy. This can be achieved by using CSS animations, Web Workers, or Web Animations APIs.

How to create efficient JavaScript animations using the Web Animations API?

The Web Animations API provides a way to create animations using JavaScript, which performs as efficiently as CSS animations. It allows you to control and manipulate animations directly from JavaScript, giving you greater flexibility than CSS animations. However, it is still an experimental technology and not fully supported by all browsers.

The above is the detailed content of 7 Performance Tips for Jank-free JavaScript Animations. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template