Chapter 10. Scheduling and Optimizing Third-Party Scripts (and AI’s Role)
Even after deciding which third-party scripts to load and when, there’s an additional layer of optimization in terms of when to execute certain work. Browsers have the capability to schedule tasks during idle periods or after the main load is done, which can help in handling third-party tasks that are not urgent. This approach ensures that noncritical third-party code runs when it won’t interfere with responsiveness or rendering.
Scheduling Third-Party Scripts
The primary tool for scheduling nonurgent work in the browser is window.requestIdleCallback.
The requestIdleCallback API
This API allows you to register a function that should run when the browser’s event loop is idle (when it has no more urgent work like layout, painting, or user input handling to do). The browser will try to execute your callback in idle gaps. You can also provide a timeout to ensure it runs eventually, even if idle time is scarce.
Here’s how to use window.requestIdleCallback:
if('requestIdleCallback'inwindow){requestIdleCallback(()=>{// Execute non-critical third-party init hereloadThirdPartyAnalytics();},{timeout:3000});}else{// Fallback: if no support, run after a delaysetTimeout(()=>loadThirdPartyAnalytics(),2000);}
This snippet schedules loadThirdPartyAnalytics() to run when the browser is idle or after a maximum of three seconds. On a fast device, it might run fairly soon (once the page is done ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access