Service Worker 201 (en)
-
Upload
chang-w-doh -
Category
Technology
-
view
217 -
download
0
Transcript of Service Worker 201 (en)
JavaScript codes run on the UI thread
means your code always:
Blocks rendering and all interactions.
Executes scripts when it alives only.
3
Web Worker and shared worker are browserfeatures for
Thread‑likely thing for running scripts:
in Background
with message‑passing
Shared Worker can be accessed from browsing contexts
4
Common rules of Web Worker
Has own global scope
Can't directly manipulate the DOM
Can't use all of properties and method in window scope
5
Service WorkerA method that enables applications to take advantage ofpersistent background processing, including hooks to enablebootstrapping of web applications while offline.
6
Service Worker is another type of worker:
But, for persistent background processing:
Having an event‑driven model
Managing installation, versions and upgrades
Generic entry point for other specifications
7
Comparisons:
Dedicated/Shared Worker and Service Worker
8
Dedicated & Shared Worker:
Runtime , Spawning , Browsing context
A thread‑like things can be created at runtime.
You should create Worker and control it at runtime.
Only available when page is loaded and created it.
You should create it at every time when wanna use it again.
9
ServiceWorker
Persistent , Installation , Browser
Daemon‑like thing can be install on system aka browser.
Lifecycle is independent from webpage or browser.
Provide version control for update from system
Nicely fits as entry‑points to Remote Notification, BackgroundSync. and so on.
10
REMINDER:
Persistent background processing is a goal of service worker,and it decided all of service worker mechanism
11
Service Worker ❤ HTTPS
For avoiding man‐in‐the‐middle‐attack However you can use 127.0.0.1 aka localhost without SSLcertificate for testing your module.
12
Dive into 201Warm‑up
Working on Offline
Installing shortcut with Web App Manifest
Push Notification
13
Warm‑up
14
Passing message
a way to interact with Worker :)
.postMessage()
.onmessage
15
Message: Client ‑> Worker
index.html
navigator.serviceWorker.controller .postMessage('hello, worker!');
sw.js
// 페이지로부터 메세지를 포스팅할 때 발생하는 이벤트입니다.self.addEventListener('message', e => { console.log('Worker got: ' + e.data);});
16
Message: Worker ‑> Client
navigator.serviceWorker .addEventListener('message', e => { console.log('page got: ' + e.data);});
sw.js
self.addEventListener('message', e => { // post Message to source client e.source.postMessage('hello, page!');});
17
serviceWorker.register()
register your own SW module and returns registration
18
Simple usage:
navigator.serviceWorker.register('/sw.js') // promise!! .then(function(registration) { // getting registeration info });
19
with option: scope
defines the scope url that this serviceworker works on.
var options = { scope: './statics'};
navigator.serviceWorker.register('/sw.js', options) .then(function(registration) { // getting registeration info });
20
importScripts()
Synchronously imports one or more scripts into the worker.
// loading single scriptself.importScripts('perfmatters.js');
// import script for arithmetic operation :)importScripts('add.js', 'minus.js', 'mult.js', 'divide.js');
21
navigator.serviceWorker has:
.getRegistration()
.getRegistrations()
.ready
.controller
22
Working on Offline
Make your own dinosaurs! :‑p
23
To implement offline web app, we'll learn:
1. Caches that you have to control
2. How to extend event lifecycle by .waitUntil()
3. fetch event as network proxy.
24
Cache Storage
An interface represents the storage for Cache objects, andreturns Promise object .
.match()
.has()
.open()
.delete()
.keys()
25
Figure. Named caches in master directories
CacheStorages│├── ServiceWorker_A│ ├── cache.1│ ├── cache.2│ └── cache.3│└── ServiceWorker_B ├── cache.1 ├── cache.2 └── cache.3
26
.waitUntil()
extends current stage
installing stage before install
activating stage before activate
27
Downloading all resources when first SW is installed.
self.addEventListener('install', function(event) { predownloadAssets().then(function() { console.log('finished downloading awesome resoures.'); });});
28
ServiceWorker will be activated before download complete.
29
Sometimes we need more time to finish current work :)
self.addEventListener('install', function(event) { // extends current stage, ̀install̀. event.waitUntil( predownloadAssets().then(function() { console.log('finished downloading awesome resoures.'); }) );});
30
.waitUntil() extends current event stage until given Promiseobject is resolved or failed.
31
.onfetch
An event handler fired whenever the browser need to fetch aresource.
32
FetchEvent
A parameter passed into .onfetch handler.
Has information about the request and resulting response
.respondWith() to back an custom response to the page
33
.respondWith()
Passing response from given response‐generating‐code parameter to origin.
self.addEventListener('fetch', function(event) { // custom response with response‐generating‐code event.respondWith( // response like typical fetch‐response model fetch(event.request) .then(function(res) { return res; }).catch(function(error) { throw error; }) );});
34
Offline sample code
Prefetching resources with install event.
Network proxy with fetch event.
35
Installing shortcut with Web App Manifest
Did you heard AndroidManifest.xml of an or .plist ?
36
Web App Manifest defines
a JSON‑based manifest file provides developers with acentralized place to put metadata associated with a webapplication: name, description, author, icon links,orientation and display mode.
37
Web App Manifest allows:
Accessing app informations for managing web app
from single JSON file has some metadata
instead of interacting with real page assets.
38
How to use it
1. Write your manifest file such as short_name , name , icons , ...
{ "short_name": "My superapp", ...}
2. Link it!
<link rel="manifest" href="YOUR_MANIFEST_URL">
39
Add to homescreen
Web app manifests provide the ability to save a site bookmarkto a device's home screen
40
Installing shortcut, launching it from homescreen like app.
41
Web App Manifest enables to get informations without loading
Displaying app icon and the name on the home screen
Launching what url when user tapped installed icon
42
Code
manifest.json
{ "name": "My super powered Web App", "short_name": "HelloWorld", "start_url": ".", "display": "standalone", "icons": [{ "src": "images/touch/homescreen48.png", "sizes": "48x48", "type": "image/png" }, // ...add your awesome data to define your web app}
43
index.html
<head> ... <title>My super powered Web App</title> ... <link rel="manifest" href="manifest.json"> ...</head>
44
Launch styling
Use the web app manifest to control the display type and pageorientation, etc. Get more information from here.
{ // Fullscreen mode, set "browser" for showing UI "display": "standalone", // Enforcing a specific orientation "orientation": "landscape", // set site‐wide theme color on the UI, addressbar "theme_color": "#2196F3"}
45
Web App Install Banner
Automatically ask user Add to homescreen
46
47
Requirements
Page should link web manifest with: short_name
name
144x144 png icon (mime type: image/png)
start_url
Service Worker
HTTPS
Be visited at least twicewith at least 5 minutes between visits.
48
For test
To ignore visit‑frequency #bypass‐app‐banner‐engagement‐checks
For desktop #enable‐add‐to‐shelf
49
Sample: manifest.json
{ "name": "My super powered Web App", "short_name": "HelloWorld", "start_url": ".", "display": "standalone", "icons": [{ "src": "images/touch/homescreen48.png", "sizes": "48x48", "type": "image/png" }, // ...awesome data to define your web app ], "related_applications": [{ "platform": "web" }, { "platform": "play", "url": "https://play.goo../details?id=com.android.chrome" }]}
50
Remote Push Notification
A long time ago in a galaxy far, far away...there are spams
51
To implement remote push message , we'll learn:
1. Push manager to access push services.
2. Push subscription that you have to control
3. Push event to handle push event
4. Push message data to resolve passing data
52
source: Web Fundamentals53
Push manager
The interface defines the operations to access push services.
subscribe(options):
getSubscription():
permissionState(options):
54
Push subscription
55
Push event
represents a push message that has been received.
sent to the global scope of a ServiceWorker aka onpush
.data contains all the information.
56
.onpush
An event when fired browser catch a push message.
57
Code
event handlers
// ̀push̀ event handler self.addEventListener('push', function(event) { console.log('Push message received', event);
event.waitUntil( // show notification self.registration.showNotification(title, description));});
// event when self.addEventListener('notificationclick', function(event) { // close notification popup event.notification.close();
// process notification things event.waitUntil(doPushNotification(event));});
58
Thank you!
60
Special thanks to
61