Update: The information in the blog post is outdated. Instead check out Progressive Web Apps made easy with ASP.NET Core.

What if you could make your ASP.NET Core web app faster to load and work offline without changing you code? You now can with the WebEssentials.AspNetCore.ServiceWorker NuGet package.

It registers a service worker that instructs the browsers how to cache resources and enable an offline experience. Most modern browsers support service workers with Edge and Safari currently implementing it.

Note, Service workers require HTTPS (except for localhost) to work.

Service workers are scripts that your browser runs in the background and act as a network proxy in the web browser to manage the web/HTTP requests programmatically

After installing the NuGet package, simply register the service in Startup.cs like so:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    services.AddServiceWorker();
}

That is all you have to do to enable service workers in your application. Here’s what it looks like with custom configuration:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    services.AddServiceWorker(new PwaOptions
    {
        Strategy = ServiceWorkerStrategy.CacheFirst,
CacheId = "v3", RoutesToPreCache = "foo.css, bar.js" }); }

Read more on the WebEssentials.AspNetCore.ServiceWorker GitHub repo about custom configuration and see how Miniblog.Core implemented it.

Progressive Web Apps

After implementing a service worker, you are now half way to turn your web app into a Progressive Web App (PWA). All you need to do is to add a JSON file called a Web App Manifest which is nothing but a few meta properties about your app such as name, description and list of icons. Here’s mine.

Comments

David

Wow! This sounds rather awesome! Will give it a try.. still waiting for the "gotcha" like "fooled you!" as it looks too good to be true :)

David
Glen

David... The "gotcha" is that for anyone using the Microsoft stack in the "real world" and having to support IE 11 for a few more years (e.g., most of us), this won't work. No support for ServiceWorker in IE 11.

Glen
Mads Kristensen

@Yura, thanks. I updated the code sample @Glen, this is a progressive enhancement which means that the site will function normally for IE 11, but newer browsers will receive an even better experience.

Mads Kristensen
Glen

@Mads, Thanks, I guess what I should have said was, "If your app *requires* offline support, versus just utilizing it as a value-add (not uncommon for an enterprise webapp), and you must support IE 11, then your best-bet is ApplicationCache/AppCache."

Glen
mike J

If I roll up my sleeves would I be able to adapt this to .NET 4.7 ?

mike J
Mads Kristensen

@mike, yes that should be possible but it might look a bit different since there are no TagHelpers and dependency injection is not the same

Mads Kristensen

Post a comment