เมื่อสร้างเว็บแอปพลิเคชันที่ซับซ้อน งานจะมีระดับความเร่งด่วนที่แตกต่างกัน การทำงานให้เสร็จสำหรับมุมมองปัจจุบันมีความสำคัญมากกว่าการส่งข้อมูลวิเคราะห์หรือการดึงข้อมูลชิ้นงานล่วงหน้า Prioritized Task Scheduling API ช่วยให้คุณกำหนดเวลาการทำงานตามลำดับความสำคัญที่เฉพาะเจาะจงได้ เพื่อให้มั่นใจว่าเบราว์เซอร์จะยังคงตอบสนองต่ออินพุตของผู้ใช้
การกำหนดเวลางานตามลำดับความสำคัญ
ใช้ scheduler.postTask() เพื่อกำหนดเวลางานโดยใช้ลำดับความสำคัญ 1 ใน 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' });
กลยุทธ์สำรอง
หากต้องการรองรับเบราว์เซอร์ที่ไม่มี 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' });
}