Als je complexe web-apps maakt, hebben taken verschillende urgentieniveaus. Het is belangrijker om taken voor de huidige weergave af te ronden dan om analytische gegevens te sturen of items vooraf op te halen. Met de Prioritized Task Scheduling API kun je werk plannen met specifieke prioriteiten, zodat de browser blijft reageren op gebruikersinvoer.
Taken plannen op prioriteit
Gebruik scheduler.postTask() om taken te plannen met een van de 3 prioriteiten:
user-blocking: Taken die gebruikersinteractie blokkeren (bijv. invoerverwerking, kritieke weergave).user-visible: Taken zijn zichtbaar voor de gebruiker, maar worden niet geblokkeerd (standaard).background: Taken die niet tijdgevoelig zijn (bijvoorbeeld analyse, vooraf ophalen).
// Schedule a high-priority task that blocks user interaction
scheduler.postTask(() => {
// DO: Handle critical updates that impact user interaction
handleCriticalUpdate();
}, { priority: 'user-blocking' });
// Schedule a default priority task
scheduler.postTask(() => {
// DO: Render non-critical content that is visible to the user
renderSecondaryContent();
}); // Defaults to 'user-visible'
// Schedule a low-priority background task
scheduler.postTask(() => {
// DO: Perform heavy background work that is not time-critical
sendAnalytics();
}, { priority: 'background' });
Reservestrategieën
Als je browsers wilt ondersteunen die de Prioritized Task Scheduling API niet hebben, moet je een polyfill gebruiken om de taakprioriteit te behouden.
// Feature detect the scheduler API
if (!('scheduler' in window && 'postTask' in window.scheduler)) {
// DO: Conditionally load the polyfill for browsers that need it
const script = document.createElement('script');
script.src = 'https://unpkg.com/scheduler-polyfill';
script.onload = () => {
// Polyfill is loaded and ready to use
runScheduledTasks();
};
document.head.appendChild(script);
} else {
runScheduledTasks();
}
function runScheduledTasks() {
// Now safe to use scheduler.postTask in all browsers
scheduler.postTask(() => {
console.log('Task with priority support');
}, { priority: 'background' });
}