按优先级安排任务

Web 功能: Scheduler API

在构建复杂的 Web 应用时,任务的紧急程度各不相同。完成当前视图的任务比发送分析数据或预提取资源更重要。借助 Prioritized Task Scheduling API,您可以安排具有特定优先级的工作,确保浏览器能够及时响应用户输入。

按优先级安排任务

使用 scheduler.postTask() 安排具有以下三种优先级之一的任务:

  • user-blocking:会阻止用户互动的任务(例如输入处理、关键渲染)。
  • user-visible:用户可见但不会阻塞的任务(默认)。
  • background:对时间不敏感的任务(例如分析、预提取)。
// 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' });

后备策略

为了支持没有 Prioritized Task Scheduling API 的浏览器,您必须使用 polyfill 来维持任务优先级。

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