優先度別にタスクのスケジュールを設定する

ウェブ機能: Scheduler API

複雑なウェブ アプリケーションを構築する場合、タスクの緊急度はさまざまです。現在のビューのタスクを完了することは、アナリティクスの送信やアセットのプリフェッチよりも重要です。Prioritized Task Scheduling API を使用すると、特定の優先度で作業をスケジュールできるため、ブラウザがユーザー入力に引き続き応答できるようになります。

優先度によるタスクのスケジュール設定

scheduler.postTask() を使用して、次の 3 つの優先度のいずれかでタスクをスケジュールします。

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

代替戦略

優先度付きタスク スケジューリング API をサポートしていないブラウザをサポートするには、ポリフィルを使用してタスクの優先度を維持する必要があります。

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