Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork61
License
madskristensen/WebEssentials.AspNetCore.ServiceWorker
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
AProgressive Web App (PWA) is a set of technologies that can be applied to any type of website and web application, and it consist of 3 components:
- Any website served over HTTPS
- AWeb App Manifest (simple JSON file)
- AService Worker JavaScript file
This components makes Web App Manifest a natural and integrated part of any ASP.NET Core web application and it comes with pre-built service workers so you don't have to write your own.
Building Progressive Web Apps have never been easier!
To add the PWA service to your ASP.NET Core 2.0 application, simply add the NuGet packageWebEssentials.AspNetCore.PWA.
Either do that through Visual Studio's NuGet Package Manager or the command line like this:
dotnet add package WebEssentials.AspNetCore.PWA
You need to do a few things to turn your website into a PWA:
- Add two image icons to your project (192x192 and 512x512)
- Add a
manifest.json
file in the root of thewwwroot
folder - Register a service in
Startup.cs
- Make sure it works
Get as many icons in various sizes as you want, but you MUST have both a 192x192 and a 512x512 size icon. Use PNG or JPEG.
Place the icons somewhere in thewwwroot
folder.
Listing the size in the file names makes them easy to identify. Example:
wwwroot/img/icon192x192.png
Consider using Real Favicon Generator to generate images for different platforms and sizes.
Add the filewwwroot/manifest.json
to your project and fill it in. It could look like this:
{"name":"Awesome Application","short_name":"Awesome","description":"The most awesome application in the world","icons": [ {"src":"/img/icon192x192.png","sizes":"192x192" }, {"src":"/img/icon512x512.png","sizes":"512x512" } ],"display":"standalone","start_url":"/"}
Read more about the various properties in theW3C specificiation.
Now your file structure will look something like this:
Inside theConfigureServices
method inStartup.cs
, add a call toservices.AddProgressiveWebApp()
like so:
publicvoidConfigureServices(IServiceCollectionservices){services.AddMvc();services.AddProgressiveWebApp();}
A
WebManifest
object is now available in the Dependency Injection system in ASP.NET Core that allows you to access the contents of the manifest.json file through the strongly typed object.
You are now done converting your website into a PWA!
If you've followed steps 1-3 then it's time to run your app in the browser and test that it is in fact a PWA. Here's how to verify it works:
Turn off JavaScript debugging in Visual Studio for the service worker to successfully register or follow thisworkaround.
Turn off JavaScript debugging fromTools > Options:
Launch the app in the Chrome browser.
View source and ensure the following element is present in<head>
:
<linkrel="manifest"href="/manifest.webmanifest"/>
The file name ismanifest.webmanifest
and notmanifest.json
because this component is handling the request instead of servingmanifest.json
directly as a static file.
If you filled in the propertytheme_color
inmanifest.json
then you'll also see this meta tag:
<metaname="theme-color"content="#ffffff"/>
Just before the</body>
end tag you'll see a script tag registering the service worker:
<script>'serviceWorker'innavigator&&navigator.serviceWorker.register('/serviceworker')</script>
Open the Chrome developer tools (F12) and navigate to theApplication tab and selectService Workers. It should look somehting like this:
If you see a service worker listed, then it was registered successfully. You may have to refresh the page in the browser to see it.
Pro tip: Make sure to check the checkbox nameUpdate on reload for a better development time experience.
ClickingManifest should show something like this:
If you see both the service worker and the manifest information then it's all working and you have now successfully converted your site to a PWA!
You can customize various settings related to both the service worker and the Web App Manifest by passing in aPwaOptions
object.
publicvoidConfigureServices(IServiceCollectionservices){services.AddMvc();services.AddProgressiveWebApp(newPwaOptions{RoutesToPreCache="/, /contact.html, data.json",Strategy=ServiceWorkerStrategy.CacheFirst});}
The same options can be set through the ASP.NET Core configuration system in appsettings.json:
{"pwa": {"registerWebmanifest":true,"routesToPreCache":"/, /contact.html, data.json","strategy":"cacheFirst" }}
This means you can have settings specific to each of your environments (development, staging, production, etc.) by using variousappsettings.<environment>.json
files or by using environment variables.
If you use Visual Studio then you should get full Intellisense inside the
pwa
object in appsettings.json.
You can use the Web App Manifest alone without the service worker by callingservices.AddWebAppManifest()
instead ofservices.AddProgressiveWebApp()
.
publicvoidConfigureServices(IServiceCollectionservices){services.AddMvc();services.AddWebAppManifest();}
By default it looks for a file namedmanifest.json
in thewwwroot
folder, but you can change the file name to whatever you like - just make sure it is located in the root of thewwwroot
folder.
If you name itmanifest.webmanifest
then you are bypassing the middleware that handles the serving of the file and instead using the Static File middleware like it was any other static file. This can be desired for certain cases, but if you're in doubt then don't name itmanifest.webmanifest
.
You can use the service worker alone without the Web App Manifest by callingservices.AddServiceWorker()
instead ofservices.AddProgressiveWebApp()
.
publicvoidConfigureServices(IServiceCollectionservices){services.AddMvc();services.AddServiceWorker();}
The options can be configured either inStartup.cs
:
publicvoidConfigureServices(IServiceCollectionservices){services.AddMvc();services.AddServiceWorker(newPwaOptions{CacheId="v3",RoutesToPreCache="foo.css, bar.js"});}
...or inappsettings.json
:
{"pwa": {"cacheId":"v1.0","routesToPreCache":"foo.css, bar.js" }}
Specify which caching strategy you want to use if you want a different one than the default (CacheFirstSafe):
publicvoidConfigureServices(IServiceCollectionservices){services.AddMvc();services.AddServiceWorker(newPwaOptions{Strategy=ServiceWorkerStrategy.CacheFirst});}
...or inappsettings.json
:
{"serviceworker": {"strategy":"cacheFirst" }}
The options are:
This strategy will add all requested resources to the service worker cache and serve it from the cache every time. If the cache doesn't have the requested resource it will fall back to the network and if that succeeds it will put the response in the cache.
This strategy, like CacheFirst, will add all requested resources to the service worker cache. Unlike CacheFirst, it has special handling for HTML files and fingerprinted resources (resources with av
querystring parameter such assite.css?v=8udsfsaufd09sud0809sd_ds
).
It will always attempt the network for HTML files (content typetext/html
) and fall back to the cache when the user is offline. That way the user always gets the latest from the live Internet when online.
For fingerprinted resources (the ones with av
querystring parameter) it will always try the cache first and fall back to the network.
This strategy only adds fingerprinted resources (resources with av
querystring parameter such as `site.css?v=8udsfsaufd09sud0809sd_ds) to the cache.
It will always try the cache for fingerprinted resources, then fall back to the network. For all other resources, it will use the network.
This strategy is useful for scenarios in which you don't wish to cache certain resources -- large video or audio files, for example -- but still wish to cache the app core assets (HTML, CSS, JS).
The minimal strategy does nothing and is good for when you only want a service worker in order for browsers to suggest installing your Progressive Web App. For this to work, you need to add aweb manifest file.
This strategy will always try the network first for all resources and then fall back to the cache when offline. When the network call succeeds, it will put the response in the cache.
This strategy is completely safe to use and is primarily useful for offline-only scenarios since it isn't giving any performance benefits.
This strategy will allow the user to specify their own implementation as a Javascript(.js) file. By default the app will search for a file namedcustomserviceworker.js
in the wwwroot folder.
A filename may be explicitly set by providing it as an option when registering the service in theStartup.cs
orappsettings.json
file.
publicvoidConfigureServices(IServiceCollectionservices){services.AddMvc();services.AddProgressiveWebApp(newPwaOptions{RegisterServiceWorker=true,Strategy=ServiceWorkerStrategy.CustomStrategy,CustomServiceWorkerStrategyFileName="myCustomServiceworkerStrategy.js"});}
When creating thecustomserviceworker.js
by providing {version}, {routes}, {ignoreRoutes} and {offlineRoute} values within the javascript file string, interpolation will be used to replace these values with option values as set in theStartup.cs
orappsettings.json
file.
(function(){//Insert Your Service Worker In place of this one!// Update 'version' if you need to refresh the cachevarversion='{version}';varofflineUrl="{offlineRoute}";varroutes="{routes}";varroutesToIgnore="{ignoreRoutes}";});
You can now specify a specific BaseURL if you plan to host your application as a Virtual Directory in IIS:
privateconststring_baseURL="/PWAApp";publicvoidConfigureServices(IServiceCollectionservices){services.AddMvc();services.AddServiceWorker(newPwaOptions{BaseRoute=_baseURL; Strategy=ServiceWorkerStrategy.CacheFirst});}publicvoidConfigure(IApplicationBuilderapp,IHostingEnvironmentenv){//...app.UsePathBase(_baseURL);//...}
...or inappsettings.json
:
{"serviceworker": {"baseRoute":"/PWAApp","strategy":"cacheFirst" }}
Make sure to update yourwwwroot/manifest.json
file:
{"name":"Awesome Application","short_name":"Awesome","description":"The most awesome application in the world","icons": [ {"src":"/PWAApp/img/icon192x192.png","sizes":"192x192" }, {"src":"/PWAApp/img/icon512x512.png","sizes":"512x512" } ],"display":"standalone","start_url":"/PWAApp/"}
About
Resources
License
Code of conduct
Contributing
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Releases
Sponsor this project
Uh oh!
There was an error while loading.Please reload this page.
Packages0
Uh oh!
There was an error while loading.Please reload this page.