عند إنشاء تطبيقات ويب معقّدة، تختلف مستويات الأولوية للمهام. يُعدّ إكمال المهام للعرض الحالي أكثر أهمية من إرسال الإحصاءات أو جلب مواد العرض مسبقًا. تتيح لك واجهة 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' });
}