Getting Started
Add install progress, controlled updates, and offline support to a Blazor WebAssembly app in six small steps.
1. Install the NuGet package
dotnet add package Bit.Bswup2. Enable static file caching (server-hosted apps)
Long-lived HTTP caching makes repeat visits and updates dramatically faster - the service worker revalidates content by hash, so stale HTTP caches are never a correctness problem.
app.UseStaticFiles(new StaticFileOptions
{
OnPrepareResponse = ctx =>
{
if (env.IsDevelopment() is false)
{
// https://bitplatform.dev/templates/cache-mechanism
ctx.Context.Response.GetTypedHeaders().CacheControl = new()
{
MaxAge = TimeSpan.FromDays(7),
Public = true
};
}
}
});3. Defer Blazor's startup
Bswup must start Blazor at the right moment (after the first install completes, or immediately when
the app is already cached), so disable auto-start on the Blazor script in your host document
(index.html or App.razor):
<!-- standalone WebAssembly app (wwwroot/index.html): -->
<script src="_framework/blazor.webassembly.js" autostart="false"></script>
<!-- Blazor Web App with Interactive WebAssembly (Components/App.razor): -->
<script src="_framework/blazor.web.js" autostart="false"></script>4. Add the Bswup script
Reference bit-bswup.js right after the Blazor script:
<script src="_content/Bit.Bswup/bit-bswup.js"
scope="/"
log="verbose"
sw="service-worker.js"
handler="bitBswupHandler"
updateInterval="3600"
updateOnVisibility="true"></script>Every attribute is optional - see the Script Options reference for all of them and their defaults.
5. Configure the service worker
Create (or edit) wwwroot/service-worker.js and wwwroot/service-worker.published.js.
The only mandatory line is the importScripts call; everything else is tuning:
// Put the same content in BOTH files:
// wwwroot/service-worker.js (used during development)
// wwwroot/service-worker.published.js (used when published)
self.assetsExclude = [/\.scp\.css$/];
self.caseInsensitiveUrl = true;
// The one mandatory line - imports the Bswup service worker engine:
self.importScripts('_content/Bit.Bswup/bit-bswup.sw.js');Then make sure the service worker is registered in your project file:
<PropertyGroup>
<ServiceWorkerAssetsManifest>service-worker-assets.js</ServiceWorkerAssetsManifest>
</PropertyGroup>
<ItemGroup>
<ServiceWorker Include="wwwroot\service-worker.js" PublishedContent="wwwroot\service-worker.published.js" />
</ItemGroup>See the Service Worker Settings reference for every available option.
6. Pick a progress UI
You have two options:
-
Use the built-in progress UI - the
BswupProgresscomponent plusbit-bswup.progress.js- and you are done. This is what this site uses. - Write your own handler function and drive any markup you like - see Events & Handler for the full event catalog and a complete sample.