AJAX - Integrating AJAX with Progressive Web App (PWA) Service Workers

Introduction

Modern web applications are expected to provide a fast, reliable, and engaging user experience, even when internet connectivity is slow or unavailable. Traditional AJAX enables web pages to communicate with servers asynchronously, allowing data to be loaded without refreshing the page. However, AJAX alone depends on an active internet connection. If the network is unavailable, AJAX requests fail, making the application unusable.

Progressive Web Apps (PWAs) solve this limitation by introducing Service Workers, which act as a proxy between the web application and the network. Service Workers can intercept AJAX requests, cache responses, serve previously stored data, and synchronize changes when the internet connection is restored.

By integrating AJAX with Service Workers, developers can build web applications that continue to function offline, load faster, and provide a user experience similar to native mobile applications.


What is a Progressive Web App (PWA)?

A Progressive Web App is a web application that uses modern browser technologies to deliver a native app-like experience.

A PWA can:

  • Work offline

  • Load quickly

  • Send push notifications

  • Install on a user's device

  • Synchronize data in the background

  • Operate across multiple platforms

PWAs combine the accessibility of websites with the functionality of mobile applications.


What is a Service Worker?

A Service Worker is a JavaScript file that runs separately from the web page.

Unlike normal JavaScript, it does not directly interact with the Document Object Model (DOM). Instead, it works in the background and handles tasks such as:

  • Caching files

  • Intercepting network requests

  • Managing offline functionality

  • Receiving push notifications

  • Background synchronization

  • Resource optimization

Because Service Workers run independently, they continue working even after the web page is closed.


Role of AJAX in PWAs

AJAX retrieves data from servers without reloading the page.

Example:

User clicks "View Products"

↓

AJAX Request

↓

Server

↓

JSON Response

↓

Page Updates

Normally, if the internet connection fails, this process stops.

With Service Workers, the request is intercepted before reaching the network.


How Service Workers Intercept AJAX Requests

A Service Worker sits between the browser and the server.

Web Application

↓

AJAX Request

↓

Service Worker

↓

Cache Check

↓

If Available
Serve Cached Data

Else

↓

Server

↓

Cache Response

↓

Return Data

This allows applications to continue working even without an internet connection.


Registering a Service Worker

The browser must register the Service Worker before it can manage AJAX requests.

Example:

if ('serviceWorker' in navigator) {
    navigator.serviceWorker.register('service-worker.js')
        .then(function(registration) {
            console.log("Service Worker Registered");
        })
        .catch(function(error) {
            console.log(error);
        });
}

Once registered, the Service Worker begins listening for network requests.


AJAX Request Without a Service Worker

User

↓

AJAX Request

↓

Internet

↓

Server

↓

Response

↓

User

If the internet is unavailable:

AJAX Request

↓

Failed

No data is displayed.


AJAX Request With a Service Worker

User

↓

AJAX Request

↓

Service Worker

↓

Cache

↓

If Data Exists

↓

Return Cached Data

Else

↓

Server

↓

Store in Cache

↓

Return Response

The application remains functional even during network interruptions.


Caching AJAX Responses

One of the primary responsibilities of a Service Worker is caching AJAX responses.

Example process:

AJAX Request

↓

Server Response

↓

Store Response in Cache

↓

Display Data

Later:

AJAX Request

↓

Cache

↓

Return Cached Data

The server does not need to be contacted again if the cached data is still valid.


Fetch Event

The Fetch Event allows the Service Worker to intercept AJAX requests.

Example:

self.addEventListener("fetch", function(event) {

});

Every network request generated by the application passes through this event.

The Service Worker decides whether to:

  • Retrieve data from the cache

  • Request fresh data from the server

  • Combine both approaches


Cache API

The Cache API stores application resources and AJAX responses locally.

Examples include:

  • HTML pages

  • CSS files

  • JavaScript files

  • Images

  • JSON responses

  • API responses

These resources remain available even when the network is unavailable.


Common Caching Strategies

Cache First

The Service Worker first checks the cache.

Cache

↓

Found

↓

Return Data

Only if the data is unavailable does it contact the server.

Suitable for:

  • Images

  • CSS

  • JavaScript

  • Static content


Network First

The Service Worker first contacts the server.

Server

↓

Success

↓

Cache New Data

↓

Return Response

If the server is unavailable:

Cache

↓

Return Cached Data

Suitable for:

  • News websites

  • Weather applications

  • Stock prices


Stale While Revalidate

This strategy provides cached data immediately while simultaneously requesting updated data from the server.

Cache

↓

Display Data

↓

Background Server Request

↓

Update Cache

Users receive instant responses while ensuring future requests have fresh data.


Cache Only

The Service Worker serves data only from the cache.

Cache

↓

Return Data

No network request is made.

Used mainly for static resources.


Network Only

Every request is sent directly to the server.

AJAX

↓

Server

↓

Response

No caching is performed.

Suitable for highly dynamic or sensitive information.


Offline Data Access

Suppose an educational website downloads lessons.

Day 1:

AJAX Downloads Lesson

↓

Cache Stores Lesson

Day 2:

Internet unavailable

Student Opens Lesson

↓

Service Worker

↓

Cache

↓

Lesson Displayed

The student continues learning without internet access.


Background Synchronization

Sometimes users perform actions while offline.

Example:

Student submits assignment

↓

No Internet

↓

Store Request

↓

Internet Restored

↓

Automatically Upload Assignment

The user does not need to submit the form again.


Handling API Responses

Suppose an AJAX request retrieves:

https://example.com/api/products

First request:

Server

↓

JSON

↓

Cache

Later:

AJAX Request

↓

Cache

↓

JSON Response

This reduces network usage and improves loading speed.


Combining AJAX with IndexedDB

Some applications store AJAX responses in IndexedDB for more advanced offline capabilities.

Process:

AJAX

↓

JSON Response

↓

IndexedDB

↓

Offline Access

IndexedDB supports larger and more structured datasets than Local Storage.


Real-World Applications

E-Commerce Websites

Online stores cache product information, allowing customers to browse previously viewed items even when offline. Shopping carts and wish lists can also be stored locally and synchronized later.


News Applications

News articles are downloaded using AJAX and cached by the Service Worker. Readers can continue accessing previously loaded articles without an internet connection.


Online Learning Platforms

Educational portals cache lessons, quizzes, videos, and notes. Students can continue studying offline, and completed activities are synchronized once connectivity returns.


Banking Applications

Some account information and transaction history can be cached securely for quick viewing. Sensitive operations still require online verification, but basic information remains accessible.


Travel Applications

Maps, hotel details, travel itineraries, and booking information are stored locally, enabling travelers to access essential information even in areas with limited connectivity.


Advantages

  • Improves application loading speed.

  • Supports offline browsing.

  • Reduces server load.

  • Decreases bandwidth usage.

  • Provides faster AJAX responses through cached data.

  • Enhances user experience during poor network conditions.

  • Supports background synchronization of user actions.

  • Enables installation as a Progressive Web App.

  • Improves reliability and responsiveness.


Limitations

  • Service Workers require HTTPS, except during local development.

  • Cached data can become outdated if not refreshed appropriately.

  • Managing cache versions requires careful planning.

  • Storage capacity varies across browsers and devices.

  • Complex caching strategies increase application complexity.

  • Certain real-time applications still require live server communication.


Best Practices

  • Register the Service Worker as early as possible in the application lifecycle.

  • Choose an appropriate caching strategy based on the type of data.

  • Cache only resources that provide value when offline.

  • Regularly update cached content to prevent stale information.

  • Use versioned caches and remove outdated cache entries.

  • Combine Service Workers with IndexedDB for storing large amounts of structured data.

  • Handle failed AJAX requests gracefully by displaying cached content or informative messages.

  • Test the application under different network conditions using browser developer tools.

  • Ensure sensitive data is not cached unless proper security measures are in place.


Conclusion

Integrating AJAX with Progressive Web App Service Workers enables developers to create modern web applications that are fast, reliable, and resilient to network disruptions. Service Workers intercept AJAX requests, intelligently cache resources, and provide offline access, while features such as background synchronization ensure that user actions are preserved and completed once connectivity is restored. This combination enhances performance, reduces server requests, and delivers a seamless user experience comparable to native applications, making it an essential technique for modern web development.