際際滷

際際滷Share a Scribd company logo
Service Worker
Overview
 What is a Service Worker?
 What existed before the Service Worker?
 Lifecycle of a Service Worker
 Use cases
 A fair assessment (a.k.a. the bad)
What is a service worker?
A service worker is a script that is run
by your browser in the background,
separate from a web page
 It's a JavaScript Worker, so it can't access the DOM
directly
 Service worker is a programmable network proxy,
allowing you to control how network requests from your
page are handled.
 It will be terminated when not in use, and restarted
when it's next needed
 Service workers are asynchronous and make extensive
use of promises
 Service workers require content to be served via https
What existed before the Service Worker?
AppCache
CACHE MANIFEST
assets/6/script/mainmin.js
assets/6/style/mainmin.css
assets/6/style/fonts/pro.ttf
assets/6/style/imgs/sprites1.png
<html manifest="offline.appcache">
Using the Service Worker
Service Worker Presentation
Service Worker Lifecycle
1. The service worker URL is fetched
and registered
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/trained-to-thrill/sw.js')
.then(function(reg) {
console.log('success!', reg);
}, function(err) {
console.log('error!', err);
});
}
2. If successful, the service worker is
executed in a ServiceWorkerGlobalScope;
this is basically a special kind of worker
context, running off the main script execution
thread, with no DOM access.
3. The service worker is now ready to
process events.
4. Installation of the worker is
attempted when service worker-
controlled pages are accessed
subsequently. An Install event is
always the first one sent to a service
worker
5. Same procedure as installing a
native app  making everything
available for use offline.
6. When the oninstall handler completes,
the service worker is considered installed.
self.oninstall = function(event) {
event.waitUntil(
caches.open('trains-static-v14').then(function(cache) {
return cache.addAll([
'/trained-to-thrill/',
'/trained-to-thrill/static/css/all.css',
'/trained-to-thrill/static/js/page.js',
'/trained-to-thrill/static/imgs/logo.svg',
'/trained-to-thrill/static/imgs/icon.png'
]);
})
);
};
7. When the service worker is installed, it
then receives an activate event. The
primary use of onactivate is for cleanup of
resources used in previous versions of a
Service Worker script.
self.onactivate = function(event) {
// remove caches beginning "trains-" that aren't in
// expectedCaches
event.waitUntil(
caches.keys().then(function(cacheNames) {
return Promise.all(
cacheNames.map(function(cacheName) {
if (!/^trains-/.test(cacheName)) {
return;
}
if (expectedCaches.indexOf(cacheName) == -1) {
return caches.delete(cacheName);
}}));}));};
8. The Service Worker will now control pages,
but only those opened after the register() is
successful. i.e. a document starts life with or
without a Service Worker and maintains that
for its lifetime. So documents will have to be
reloaded to actually be controlled.
this.addEventListener('fetch', function(event) {
var cachedResponse = caches.match(event.request).catch
(function() {
return event.default().then(function(response) {
return caches.get('v1').then(function(cache) {
cache.put(event.request, response.clone());
return response;
});
});
}).catch(function() {
return caches.match('/sw-test/gallery/myLittleVader.jpg');
});
event.respondWith(cachedResponse);
});
When to use?
Cache assets specific to the version of
the app
Give the user a "Read later" or "Save
for offline" button. When it's clicked,
fetch what you need from the network &
pop it in the cache.
On network response: Frequently
updating resources such as a user's
inbox, tweets, images, or article
contents.
Push
 The Push API is built on top of SerivceWorker.
 Allows the ServiceWorker to be awoken in response to
a message from the OS's messaging service.
 Happens even when the user doesn't have a tab open
to your site, only the ServiceWorker is woken up.
 You request permission to do this from a page & the
user will be prompted.
Background Sync
 Built on top of ServiceWorker.
 It allows you to request background data
synchronisation as a one-off, or on an (extremely
heuristic) interval.
 This happens even when the user doesn't have a tab
open to your site, only the ServiceWorker is woken up.
 You request permission to do this from a page & the
user will be prompted.
The bad news
Service Worker Presentation
 If installation fails, the browser is not good at
telling you about it
 fetch() is only available in service workers
 No credentials by default (cookies)
 Non-CORS fail by default (opaque response)
 Handling responsive images
Demo
Questions

More Related Content

What's hot (20)

PPT
Real Time Communication using Node.js and Socket.io
Mindfire Solutions
PDF
Recorrido por el Content Repository API para Java (JCR), analizando JackRabbit
Magnolia
PDF
Introduction to Progressive web app (PWA)
Zhentian Wan
PDF
Introduction To Single Page Application
KMS Technology
PDF
= メ梶 Django admin
KyeongMook "Kay" Cha
PDF
Javascript and DOM
Brian Moschel
PDF
REST APIs with Spring
Joshua Long
PDF
Spring Boot
HongSeong Jeon
PDF
jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...
Edureka!
PDF
Spring security oauth2
axykim00
PPTX
Asp.net and .Net Framework ppt presentation
abhishek singh
PPT
Spring ppt
Mumbai Academisc
PPTX
Progressive Web Apps and React
Mike Melusky
PPTX
Lab #2: Introduction to Javascript
Walid Ashraf
PPTX
jQuery PPT
Dominic Arrojado
PPTX
Express js
Manav Prasad
PDF
REST API and CRUD
Prem Sanil
PDF
MongoDB and Node.js
Norberto Leite
PDF
Express node js
Yashprit Singh
PPTX
Angular modules in depth
Christoffer Noring
Real Time Communication using Node.js and Socket.io
Mindfire Solutions
Recorrido por el Content Repository API para Java (JCR), analizando JackRabbit
Magnolia
Introduction to Progressive web app (PWA)
Zhentian Wan
Introduction To Single Page Application
KMS Technology
= メ梶 Django admin
KyeongMook "Kay" Cha
Javascript and DOM
Brian Moschel
REST APIs with Spring
Joshua Long
Spring Boot
HongSeong Jeon
jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...
Edureka!
Spring security oauth2
axykim00
Asp.net and .Net Framework ppt presentation
abhishek singh
Spring ppt
Mumbai Academisc
Progressive Web Apps and React
Mike Melusky
Lab #2: Introduction to Javascript
Walid Ashraf
jQuery PPT
Dominic Arrojado
Express js
Manav Prasad
REST API and CRUD
Prem Sanil
MongoDB and Node.js
Norberto Leite
Express node js
Yashprit Singh
Angular modules in depth
Christoffer Noring

Similar to Service Worker Presentation (20)

PPT
Intro to Service Worker API and its use cases
satejsahu
PDF
Service worker API
Giorgio Natili
PDF
"Service Worker: Let Your Web App Feel Like a Native "
FDConf
PDF
[1C1]Service Workers
NAVER D2
PDF
ServiceWorker: New game changer is coming!
Chang W. Doh
PPTX
Service workers and the role they play in modern day web apps
Mukul Jain
PDF
Service workers
Pavel Zhytko
PDF
Updates on Offline: My AppCache wont come back and ServiceWorker Tricks ...
Natasha Rooney
PDF
Maxim Salnikov - Service Worker: taking the best from the past experience for...
Codemotion
PDF
JQuery UK February 2015: Service Workers On Vacay
Natasha Rooney
PDF
JQuery UK Service Workers Talk
Natasha Rooney
PPTX
Introduction to Service Workers | Matteo Manchi
Codemotion
PPTX
Progressive Web Apps 101
Muhammad Samu
PDF
FirefoxOS Meetup - Updates on Offline in HTML5 Web Apps
Natasha Rooney
PPTX
Building Offline Ready and Installable Web App
Muhammad Samu
PDF
PWA Service Worker
Anna Su
PPTX
GDG Ibadan #pwa
Gbolahan Alli
PDF
Service workers
Eugene Lazutkin
PDF
Service workers are your best friends
Antonio Peric-Mazar
PDF
Service worker: discover the next web game changer
Sandro Paganotti
Intro to Service Worker API and its use cases
satejsahu
Service worker API
Giorgio Natili
"Service Worker: Let Your Web App Feel Like a Native "
FDConf
[1C1]Service Workers
NAVER D2
ServiceWorker: New game changer is coming!
Chang W. Doh
Service workers and the role they play in modern day web apps
Mukul Jain
Service workers
Pavel Zhytko
Updates on Offline: My AppCache wont come back and ServiceWorker Tricks ...
Natasha Rooney
Maxim Salnikov - Service Worker: taking the best from the past experience for...
Codemotion
JQuery UK February 2015: Service Workers On Vacay
Natasha Rooney
JQuery UK Service Workers Talk
Natasha Rooney
Introduction to Service Workers | Matteo Manchi
Codemotion
Progressive Web Apps 101
Muhammad Samu
FirefoxOS Meetup - Updates on Offline in HTML5 Web Apps
Natasha Rooney
Building Offline Ready and Installable Web App
Muhammad Samu
PWA Service Worker
Anna Su
GDG Ibadan #pwa
Gbolahan Alli
Service workers
Eugene Lazutkin
Service workers are your best friends
Antonio Peric-Mazar
Service worker: discover the next web game changer
Sandro Paganotti
Ad

Service Worker Presentation

  • 2. Overview What is a Service Worker? What existed before the Service Worker? Lifecycle of a Service Worker Use cases A fair assessment (a.k.a. the bad)
  • 3. What is a service worker?
  • 4. A service worker is a script that is run by your browser in the background, separate from a web page
  • 5. It's a JavaScript Worker, so it can't access the DOM directly Service worker is a programmable network proxy, allowing you to control how network requests from your page are handled. It will be terminated when not in use, and restarted when it's next needed Service workers are asynchronous and make extensive use of promises Service workers require content to be served via https
  • 6. What existed before the Service Worker?
  • 12. 1. The service worker URL is fetched and registered if ('serviceWorker' in navigator) { navigator.serviceWorker.register('/trained-to-thrill/sw.js') .then(function(reg) { console.log('success!', reg); }, function(err) { console.log('error!', err); }); }
  • 13. 2. If successful, the service worker is executed in a ServiceWorkerGlobalScope; this is basically a special kind of worker context, running off the main script execution thread, with no DOM access. 3. The service worker is now ready to process events.
  • 14. 4. Installation of the worker is attempted when service worker- controlled pages are accessed subsequently. An Install event is always the first one sent to a service worker 5. Same procedure as installing a native app making everything available for use offline.
  • 15. 6. When the oninstall handler completes, the service worker is considered installed. self.oninstall = function(event) { event.waitUntil( caches.open('trains-static-v14').then(function(cache) { return cache.addAll([ '/trained-to-thrill/', '/trained-to-thrill/static/css/all.css', '/trained-to-thrill/static/js/page.js', '/trained-to-thrill/static/imgs/logo.svg', '/trained-to-thrill/static/imgs/icon.png' ]); }) ); };
  • 16. 7. When the service worker is installed, it then receives an activate event. The primary use of onactivate is for cleanup of resources used in previous versions of a Service Worker script. self.onactivate = function(event) { // remove caches beginning "trains-" that aren't in // expectedCaches event.waitUntil( caches.keys().then(function(cacheNames) { return Promise.all( cacheNames.map(function(cacheName) { if (!/^trains-/.test(cacheName)) { return; } if (expectedCaches.indexOf(cacheName) == -1) { return caches.delete(cacheName); }}));}));};
  • 17. 8. The Service Worker will now control pages, but only those opened after the register() is successful. i.e. a document starts life with or without a Service Worker and maintains that for its lifetime. So documents will have to be reloaded to actually be controlled. this.addEventListener('fetch', function(event) { var cachedResponse = caches.match(event.request).catch (function() { return event.default().then(function(response) { return caches.get('v1').then(function(cache) { cache.put(event.request, response.clone()); return response; }); }); }).catch(function() { return caches.match('/sw-test/gallery/myLittleVader.jpg'); }); event.respondWith(cachedResponse); });
  • 19. Cache assets specific to the version of the app
  • 20. Give the user a "Read later" or "Save for offline" button. When it's clicked, fetch what you need from the network & pop it in the cache.
  • 21. On network response: Frequently updating resources such as a user's inbox, tweets, images, or article contents.
  • 22. Push The Push API is built on top of SerivceWorker. Allows the ServiceWorker to be awoken in response to a message from the OS's messaging service. Happens even when the user doesn't have a tab open to your site, only the ServiceWorker is woken up. You request permission to do this from a page & the user will be prompted.
  • 23. Background Sync Built on top of ServiceWorker. It allows you to request background data synchronisation as a one-off, or on an (extremely heuristic) interval. This happens even when the user doesn't have a tab open to your site, only the ServiceWorker is woken up. You request permission to do this from a page & the user will be prompted.
  • 26. If installation fails, the browser is not good at telling you about it fetch() is only available in service workers No credentials by default (cookies) Non-CORS fail by default (opaque response) Handling responsive images
  • 27. Demo