पाठ 14 / 29
Background Sync
Background sync को implement करें ताकि user data को reliably deliver किया जा सके भले ही connection खो जाए।
Reliable Data Delivery
Background sync user actions (form submissions, file uploads) को queue करता है और जब connection restore होता है तो उन्हें retry करता है। Browser retries को handle करता है, आपके app को नहीं।
Background sync को register करें
Background sync के लिए एक task को queue करें और service worker में इसे handle करें।
// In page
navigator.serviceWorker.ready.then(reg => {
reg.sync.register('submit-form').then(() => {
console.log('Sync registered');
});
});
// In service worker
self.addEventListener('sync', event => {
if (event.tag === 'submit-form') {
event.waitUntil(
fetch('/api/submit', { method: 'POST', body: formData })
.catch(() => Promise.reject())
);
}
});
Output:
Form submission retried automatically when connection is restored.
एक आम गलती
Background sync केवल service worker में काम करता है और proper error handling की जरूरत है। Failed syncs को exponential backoff के साथ retry किया जाता है।
Handling Sync Failures and Retries
Proper retry logic और user feedback के साथ resilient sync को implement करें।