A requestIdleCallback shim/polyfill
requestIdleCallbackpolyfill/shim
This is a polyfill/shim for the
requestIdleCallbackand
cancelIdleCallbackAPI. Also fixes early API implementation.
For more information see the Cooperative Scheduling of Background Tasks Draft.
Include the "index.js" in your website and use
requestIdleCallbackand
cancelIdleCallbackaccording to the specification.
requestIdleCallbackcan't be really polyfilled. Therefore
requestIdleCallbackbasically includes a throttle like function, that uses some heuristics to detect a) long running frames and b) user input as also DOM mutations to adapt accordingly.
requestIdleCallbackalso tries to get the time right after a frame commit. The
deadline.timeRemaining()either starts with 7ms or with 22ms for the first scheduled callback.
If multiple functions are scheduled with the
requestIdleCallbackshim for the same idle time, the shim makes sure to split those functions as soon as
timeRemaining()is exceeded.
If you have a fast or a non-splittable task:
requestIdleCallback(function(){ //your task });
In case you have a heavy and splittable task you can use efficient script yielding technique:
requestIdleCallback(function(deadline){ while(tasks.length && deadline.timeRemaining() > 0){ tasks.shift()(); }if(tasks.length){ requestIdleCallback(runTasks); }
});
Reading vs writing layout:
requestIdleCallbackis mainly for layout neutral or layout reading/measuring tasks. In case you want to write layout/manipulate the DOM consider using
requestAnimationFrameinstead.
Of course
requestIdleCallbackcan also be combined with
requestAnimationFrame:
requstIdleCallback(function(){ var width = element.offsetWidth;requestAnimationFrame(function(){ element.classList[width > 600 ? 'add' : 'remove']('is-large'); });
});