Khi xây dựng các ứng dụng web phức tạp, các tác vụ sẽ có mức độ khẩn cấp khác nhau. Việc hoàn thành các tác vụ cho chế độ xem hiện tại quan trọng hơn việc gửi số liệu phân tích hoặc tìm nạp trước thành phần. API Lập lịch tác vụ ưu tiên cho phép bạn lập lịch công việc với các mức độ ưu tiên cụ thể, đảm bảo trình duyệt luôn phản hồi hoạt động đầu vào của người dùng.
Lên lịch cho các tác vụ theo mức độ ưu tiên
Sử dụng scheduler.postTask() để lên lịch cho các tác vụ theo một trong ba mức độ ưu tiên:
user-blocking: Các tác vụ chặn hoạt động tương tác của người dùng (ví dụ: xử lý hoạt động đầu vào, kết xuất quan trọng).user-visible: Người dùng có thể thấy các tác vụ nhưng không bị chặn (mặc định).background: Các tác vụ không quan trọng về thời gian (ví dụ: phân tích, tìm nạp trước).
// 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' });
Chiến lược dự phòng
Để hỗ trợ các trình duyệt không có API Lập lịch tác vụ theo mức độ ưu tiên, bạn phải sử dụng polyfill để duy trì mức độ ưu tiên của tác vụ.
// 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' });
}