Course contentsShow
← Web Development
Lesson 2721 of 2,98248. File Uploads and HandlingFree lesson

Background Upload with Service Workers

Use service workers to continue file uploads even when the user closes or navigates away from the page.

Background Upload with Service Workers

You'll learn how to use service workers to keep file uploads running even after the user closes your page or navigates elsewhere.

The Problem with Normal Uploads

Normally, when a user uploads a file and then closes the browser tab or navigates away, the upload immediately stops. The JavaScript running in the page dies along with it. For large files or slow connections, this creates a frustrating user experience where people must keep your page open until the upload finishes.

Service Workers to the Rescue

Service workers run independently of web pages—they're background scripts that persist even when no tabs are open. By handing off an upload to a service worker, the upload can continue in the background.

Think of it like giving your mail to a postal worker instead of personally walking it to the destination. Once handed off, you're free to leave—the postal worker will finish the job.

The Background Sync API

Service workers use the Background Sync API to queue uploads. When your page initiates an upload, you register a sync event with the service worker. Even if the page closes immediately, the service worker wakes up later to complete the upload:

// In your page
navigator.serviceWorker.ready.then(registration => {
  return registration.sync.register('upload-file');
});

// In your service worker
self.addEventListener('sync', event => {
  if (event.tag === 'upload-file') {
    event.waitUntil(performUpload());
  }
});

The service worker retrieves queued file data (from IndexedDB or Cache API), performs the upload via fetch(), and handles success/failure independently.

Real-World Benefits

This pattern is essential for mobile users with unreliable connections, large file uploads, and progressive web apps that feel more like native applications.

Key Takeaway: Service workers with Background Sync API decouple uploads from the page lifecycle, allowing file transfers to complete even when users navigate away or close your app.