Programar tarefas por prioridade

Recursos da Web: API Scheduler

Ao criar aplicativos da Web complexos, as tarefas têm diferentes níveis de urgência. Concluir tarefas para a visualização atual é mais importante do que enviar análises ou fazer a pré-busca de recursos. A API Prioritized Task Scheduling permite programar tarefas com prioridades específicas, garantindo que o navegador continue respondendo às interações do usuário.

Agendamento de tarefas por prioridade

Use scheduler.postTask() para programar tarefas com uma das três prioridades:

  • user-blocking: tarefas que bloqueiam a interação do usuário (por exemplo, processamento de entrada, renderização crítica).
  • user-visible: tarefas visíveis para o usuário, mas que não bloqueiam (padrão).
  • background: tarefas que não são urgentes (por exemplo, análise, pré-busca).
// 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' });

Estratégias de fallback

Para oferecer suporte a navegadores que não têm a API Prioritized Task Scheduling, use um polyfill para manter a priorização de tarefas.

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