In this lesson, you will learn how to transform your Blazor WebAssembly application into a Progressive Web App (PWA) to enable offline capabilities and a native-like install experience.
Understanding the PWA Architecture
A PWA relies on two primary pillars to function without a network connection: the Web App Manifest and the Service Worker.
The manifest.json file is a simple configuration file that tells the browser how your app should look when installed on a device—such as its name, icons, and starting URL. You can find this in your wwwroot folder. It essentially turns your website into an "app" that can live on a user's home screen.
The Service Worker, defined in service-worker.js, is the engine that enables offline support. It acts as a proxy between your app and the network. When your Blazor app loads, the service worker intercepts requests for your assets (like DLLs, CSS, and HTML) and caches them locally. The next time the user visits, the service worker serves these assets from the browser's cache, allowing the app to start even if the device is completely offline.
Configuring for Offline
When you create a Blazor WebAssembly project with the PWA template, the framework generates a service-worker.published.js file for you. This file uses the assets-manifest.json to know exactly which files to cache.
To customize what gets cached, you would modify the list in your service-worker.published.js:
const assetsInclude = [/\.dll$/, /\.pdb$/, /\.wasm/, /\.html/, /\.js$/, /\.json$/, /\.css$/, /\.woff$/, /\.png$/, /\.jpe?g$/, /\.gif$/, /\.ico$/];
self.addEventListener('fetch', event => {
// Only handle GET requests
if (event.request.method !== 'GET') return;
// Use Cache-First strategy for cached assets
event.respondWith(caches.match(event.request).then(response => {
return response || fetch(event.request);
}));
});
By using a "cache-first" strategy, the service worker checks the browser cache before attempting to reach the network. If the user is offline, the fetch fails, but the cache returns the previously stored version, ensuring your Blazor UI remains interactive.
Key Takeaway: PWA integration in Blazor uses a manifest for app identity and a service worker to intercept network requests, enabling your app to cache its own resources and run reliably without an internet connection.