依優先順序排定工作

網頁功能: Scheduler API

建構複雜的網頁應用程式時,工作會有不同的緊急程度。完成目前檢視畫面的工作,比傳送數據分析或預先擷取素材資源更重要。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' });
}