ASP.NET Core 2.2 - PWA Offline Cache
This article will demonstrate creating a styled Offline page and updating the service worker's cache using an editable copy of the default service worker provided by the WebEssentials.AspNetCore.PWA NuGet package. I will assume you have created a new ASP.NET Core 2.2 Razor Pages project, have successfully installed the WebEssentials.AspNetCore.PWA package and have created an editable copy of the service worker. I won't use Identity or Individual User Accounts.
The WebEssentials.AspNetCore.PWA NuGet package dynamically creates an offline.html file which is displayed when the application is offline, and the resource has not been cached. It has little styling.
Section reference:
To test the offline page, you can check the Offline checkbox in DevTools > Application > Service Workers.
Verify the Privacy page is not cached. Select the v1.0::CacheFirstSafe in DevTools > Application > Cache Storage.
Browse the Privacy page.
Let's create and cache a new offline page. Create a new razor page in the Pages folder named Offline which does not need a PageModel class but uses the layout page from _ViewStart.cshtml.
Edit Offline.cshtml:
@page @{ ViewData["Title"] = "Offline"; } <h1>@ViewData["Title"]</h1> <p>This page was not cached before you went offline.</p>
Configure the service worker to use the new offline route and update the cache version to start a new offline cache. For more on caching strategies see the Article references.
Edit pwa-serviceworker.js:
// Update 'version' if you need to refresh the cache var version = 'v1.1::CacheFirstSafe'; var offlineUrl = "/Offline";
The first time you execute the application after you have modified the service worker, the new service worker is loaded but not activated.
The new cache is initialized with the new Offline page.
Close all application browser tabs. The new service worker will not activate until the old service worker is idle. Restart the application. The old cache is gone, and the new cache is active.
Check the Offline option for the service workers and browse the non-cached Privacy page. You can browse the home page offline because it was cached.
Update 08/29/2019
Moved update notices towards the bottom of the article.
Update 07/28/2019
Added spaces to the link text in the article references. Fixes a responsive width issue on small screens.
Comments(0)