Usually, I try to make all of my visual effects with CSS. But sometimes, be it by explicit client request or because the desired effect is too complicated for CSS, I need to use JS libraries. One such example is Particles.js .
Despite the description stating it to be lightweight, using it significantly impacts my PageSpeed Insights score. For example, take a look at the Insights for the library's demo page , which is pretty simple. The overall score is pretty good, thanks to the page's simplicity, but both rendering and script evaluation times are high.
If I don't have any control over the library itself and there isn't a more efficient library available*, what can I do to improve performance?
What methods can I use to minimize the impact that such a heavy visual effects script has? Can I, for example, only load the effect if the device is powerful enough to handle it? Is it possible to de-prioritize the effect so that any lag won't affect the rest of the page?
*That may or may not be the case for this particular library, but let's assume there isn't a better one.
Using the requestAnimationFrame (and libraries that use it) will always add to the render and script evaluation time. This is not necessarily a bad thing, but you don't always have control over an external library.
One option is to add a layer to the animation. Something like this will add very little overhead to the animation, but will cancel it if the frame rate starts dipping down:
It looks something like this:
let startTime = Performance.now() // precise start time
const animation = new MyAnimationLib()
const updateLoop = newTime => {
const delta = newTime - startTime
startTime = newTime
if (delta > 1000 / 60) {
animation.cancel() // 60 fps min to keep running animation
return // exit the loop
}
requestAnimationFrame(updateLoop)
}
// Start monitoring the animation
requestAnimationFrame(updateLoop)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.