Pianifica le attività in base alla priorità

Funzionalità web: API Scheduler

Quando si creano applicazioni web complesse, le attività hanno diversi livelli di urgenza. Il completamento delle attività per la visualizzazione corrente è più importante dell'invio di dati di analisi o del precaricamento degli asset. L'API Prioritized Task Scheduling consente di pianificare il lavoro con priorità specifiche, garantendo che il browser rimanga reattivo all'input dell'utente.

Pianificazione delle attività in base alla priorità

Utilizza scheduler.postTask() per pianificare le attività con una delle tre priorità:

  • user-blocking: attività che bloccano l'interazione dell'utente (ad es. gestione degli input, rendering critico).
  • user-visible: le attività sono visibili all'utente, ma non bloccanti (impostazione predefinita).
  • background: attività che non sono urgenti (ad es. analisi, precaricamento).
// 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' });

Strategie di riserva

Per supportare i browser che non dispongono dell'API Prioritized Task Scheduling, devi utilizzare un polyfill per mantenere la priorità delle attività.

// 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' });
}