The good news is that there’s now an API that can help:
requestIdleCallback. In the same way that adopting
requestAnimationFrameallowed us to schedule animations properly and maximize our chances of hitting 60fps,
requestIdleCallbackwill schedule work when there is free time at the end of a frame, or when the user is inactive. This means that there’s an opportunity to do your work without getting in the user’s way.
Why should I use requestIdleCallback?
Scheduling non-essential work yourself is very difficult to do. It’s impossible to figure out exactly how much frame time remains because after
requestAnimationFramecallbacks execute there are style calculations, layout, paint, and other browser internals that need to run. A home-rolled solution can’t account for any of those. In order to be sure that a user isn’t interacting in some way you would also need to attach listeners to every kind of interaction event (
click), even if you don’t need them for functionality, just so that you can be absolutely sure that the user isn’t interacting. The browser, on the other hand, knows exactly how much time is available at the end of the frame, and if the user is interacting, and so through
requestIdleCallbackwe gain an API that allows us to make use of any spare time in the most efficient way possible.
The Cooperative Scheduling of Background Tasks API (also referred to as the Background Tasks API or simply the
requestIdleCallback()API) provides the ability to queue tasks to be executed automatically by the user agent when it determines that there is free time to do so.