SlideShare uma empresa Scribd logo
1 de 47
Baixar para ler offline
JavaScript!
!
Multithreading



Everybody knows Javascript is single-threaded and that it shares this same thread with other
browser-related processes such as painting and compositing. There are several techniques to
implement pseudo multithreading in JavaScript; however, during this talk we will focus our attention
on how to use and debug the Service Worker API. Our end goal is to explore practical use cases in
order to simplify the process to render complex user interfaces and transitions in a browser.
@giorgionatili
Giorgio !
Natili!
Lead of Mobile Engineering!
!
Giorgio is an author, educator, community leader and Lead
UI Engineer in McGraw Hill Education, a publisher of print
and digital information services for the academic,
professional and library markets. Giorgio was also the
founder of GNStudio, a boutique Rome-based development
and design studio specializing in engaging and accessible
web and mobile experiences. A strong proponent of agile
development practices, Giorgio's areas of expertise include
standards-based application development, client-side
scripting, gaming, and video streaming.

ANDROID
IOS (SWIFT)
JAVASCRIPT
CORDOVA
TDD + BDD
WEBRTC
@giorgionatili
http://www.meetup.com/pro/mobiletea/
We are hiring!!!

Send your resume to: meirav@tegrity.com
Today’s!
Agenda
Offline Web Application
Why offline is not a failure, and why we should embrace offline
scenarios as an opportunity.
Service Workers
Discover how a service worker works, understand the main
gotchas to start with, and how to use the API today, especially in
mobility.
Multithreading Javascript
Explore how to create even more scalable web apps using service
workers and how to delegate networking and other expensive
operations to “external” entities.
Additional!
Thoughts
Offline !
Web
Applications
Offline!
WebApps !
is an Old!
Topic • Occasionally connected computing
literature dates back to the 1970s.

• Macromedia tried to enable offline
with Central 

• A List Apart discussed these
techniques in 2013
Lack of
Connectivity is
not an Error
• Don’t treat a lack of connectivity like an error.

• Apps should be able to handle dropped
connections.
!
• Apps should keep minimal functionalities
when offline.
Offline Statuses
Desktop!
Laptops!
Mobile!
Devices
What is the most important
capability shared between these
devices?
All of them can be offline!
Offline is a
New
Opportunity
• Designing apps and their interfaces for
intermittent connectivity leads to an
abundance of new scenarios and
problems.
!
• Solving all of them means that your app
should preempting users’ needs.
Review Your
Architecture
Separation Of Concerns Resource OptimizationData Request Flow
In order to implement a successful offline strategy
it’s mandatory to define clear boundaries between
UI elements, logic and content.
An app is nothing without data; however, a well
organized data request flow can offer a good
experience also in offline mode.
Caching spaces are limited; optimizing images,
CSS, JS files, etc. is a very important phase of
the re-architecture.
There isn’t an app that cannot be improved. Iterating in
a collaborative way over and over is the preferred way
to evolve architectures.!


However, bad architectures exist. Don’t be scared to
start over embracing the “offline first” approach!
Identify Clearly
The App
Layers
03. Bundles
Optimizing the UI for different screens means also feeding the
app with appropriately compressed images, this consideration is
the key to avoid issues with caches size.
04. User Interface
Be sure to decouple components as much as possible;
otherwise caching the dependencies will proof difficult when
implementing any strategy.
01. Communication Layer
Use the fetch API and avoid implementing a call-back pyramid
of doom; take advantage of the Promises and of their sequential
syntax.
02. Network Layer
Avoid a single bundle; breaking down the app in more than a
single monolithic bundle will be the key for a layered caching
strategy.
Thinking!
Offline!
Native Experience
Think to the offline re-architecture as an
opportunity to handle your app as if it
were a native one.
Better Functionalities
The reviewed architecture will help you to
handle gracefully the points of failures
(POF) of your app.
Future Proof
Handling remote requests with offline use
in mind will help you to integrate the fetch
API.
Service!
Workers
Workers in a
Nutshell
Web Workers
Web workers provide a simple means for web content to run
scripts in background threads. The worker thread can perform
tasks without interfering with the user interface.!
Shared Workers
A shared worker is a specific kind of worker that can be accessed
from several browsing contexts, such as several windows,
iFrames, or even workers (in the same domain).
Service Workers
Service workers are event-driven workers that act as proxy
servers that sit between web applications, the browser, and the
network (when available).
A Quick
Overview
• The ServiceWorkers API allows us to
make sites work offline through
intercepting network requests and
programmatically telling the browser
what to do with these requests.

• This API works in Chrome and other
browsers (https://github.com/coonsta/
cache-polyfill)
!
• chrome://inspect/#service-workers
Features
• The killer feature in the ServiceWorker API is the
offline “first” nature.

• A service worker is a background worker (easy
multi-threading).

• The API allows us to implement background sync,
geofencing and network control.
WebWorker!
Lifecycle
• On install (as a dependency or not)

• On activate

• On push message

• On background-sync
!
• On terminate
Registering a !
Service!
Worker
let sw = navigator.serviceWorker;



sw.register('service-worker.js',


{scope: './'}).then(function(registration) {
!
// Handle the installation gracefully
!
});
self.addEventListener('install', function(event) {
event.waitUntil(
caches.open('static-v3').then(function(cache) {
return cache.addAll([

!
'/css/whatever-v3.css',
'/css/img/sprites-v6.png',
'/css/fonts/whatever-v8.woff',
'/js/all-min-v4.js'

!
// Whatever your app needs to run
!
]);
})
);
});
Service Worker!
Installation!
Not Blocking!
Installing
self.addEventListener('install', function(event) {
event.waitUntil(
caches.open('assets-core-v1').then(function(cache) {
cache.addAll(
!
// Optional assets
);
})
);
});
Service Worker!
Activation
self.addEventListener('activate', function(event) {
event.waitUntil(
caches.keys().then(function(cacheNames) {
return Promise.all([
!
// It happens when the page reload or
// when a new version is installed
// It’s the best place to manage the caches
]);
})
);
});
Service Worker!
Fetch
self.addEventListener('fetch', function(event) {
event.respondWith(
caches.match(event.request).then(function(response) {
// Return network with cache fallback
// Basic, CORS or Opaque responses
return response || fetch(event.request);
})
);
});
Service Worker!
Notification
self.addEventListener('push', function(event) {
if (event.data.text() == 'new-tweet') {
!
// Handle caches and prepare the content for the view
!
}});
!
self.addEventListener('notificationclick', function(event) {
if (event.notification.tag == 'new-tweet') {
!
// Assume that all of the resources needed to render
// the 'inbox' have previously been cached
!
new TweetView('inbox');
}
});
Service Worker!
Background
Sync
self.addEventListener('sync', function(event) {
if (event.id == 'update-leaderboard') {

// Or whatever promise that sync the data
return openBgSyncDB();
});
Security!
!
During development you'll be
able to use service worker
through localhost;
however, to deploy it on a
site, you'll need to set up
HTTPS on your server.
No Extra!
Tests
• A ServiceWorker returns eventually cached
results.!
• Emulating offline the tests previously written
should fulfill without any extra effort.
Debugging!
!
You can debug a service worker with
the standard Chrome DevTools
!
(Note: debug in an incognito window)
Mobile Support
It’s Complicated!
Browsers Support
(I am really confident about IE!)
// Include SW cache polyfill
importScripts("js/serviceworker-cache-polyfill.js");
Size!
Matters
• Your origin is given a certain amount of
free space to use as it sees fit.
!
• That free space is shared between all
origin storage: LocalStorage,
IndexedDB, Filesystem, and Caches.
!
• The amount you get isn't specified; it
will differ depending on device and
storage conditions.
Multithreading
JavaScript
JavaScript !
is !
Multithread
• Tasks are scheduled so the browser can get from its internals
into JavaScript/DOM land and ensures these actions happen
sequentially. Between tasks, the browser may render updates.!
!
• Microtasks are usually scheduled for things that should
happen straight after the currently executing script, such as
reacting to a batch of actions, or to make something async
without taking the penalty of a whole new task
JavaScript!
Schedule in
Practice
•script start
•script end
•promise1
•promise2
•setTimeout
JavaScript!
Schedule in
Practice
Web & Shared
Workers
Scenarios!
• Image processing!
• Large amount of data recovery!
• Text analysis !
• Complex algorithms (e.g. adaptive learning)!
• Game engines!
• Angular digest cycle (why not ?!?)
Service
Workers
Scenarios
!
• Offline applications!
• Performance improvement!
• Notifications!
• Background updating
01.
02.
03. 04.
Workers!
Based!
Architecture
03. Service Workers
Delegate to the Workers process intensive operations
such as data parsing and massaging, expensive
network request, etc.
04. Web & Shared Workers
Split the business logic in self-contained components to help
reduce dependencies; eventually bundle together layers of the
app when it’s too complicated to reduce the dependencies.
01. Business Logic
Create a communication bridge between components!
and the worker layers using events and the!
postMessage API.
02. Communication Layer
Use the Service Worker(s) to handle the cache of the
shell needed to render the app also in offline mode.
Useful Links and Resources
• The offline cookbook https://jakearchibald.com/2014/offline-cookbook/!
• The fetch() API https://developers.google.com/web/updates/2015/03/introduction-to-fetch?hl=en!
• Designing offline first apps http://alistapart.com/article/offline-first!
• Using WebWorker with Angular https://andywalpole.me/#!/blog/142677/using-web-workers-angularjs!
• A simple ServiceWorker app http://blog.lamplightdev.com/2015/01/06/A-Simple-ServiceWorker-App/ !
• Introduction to ServiceWorker http://www.html5rocks.com/en/tutorials/service-worker/introduction/!
• Progressive networking https://ponyfoo.com/articles/progressive-networking-serviceworker!
• ServiceWorker explained https://github.com/slightlyoff/ServiceWorker/blob/master/explainer.md !
• Application shell architecture https://medium.com/google-developers/instant-loading-web-apps-with-an-application-shell-
architecture-7c0c2f10c73#.9ld0u2liz !
• Sending an app to the browser https://surge.sh/!
• Hoodie use case http://hood.ie/blog/minutes-offline-case-study.html
Offline 

First!
Summary!
Review Code, Design & Content
Clearly identify code responsibilities, decouple
code from design, define the boundaries between
content and UI, etc.
Refactor & Enhance Code
Clean the code, decouple components from each
other, expose clear APIs, take advantage of
Promises, etc.
Handle Network Failure
Determine what the app needs to run without network
connection, handle the use cases in Workers,
progressively enhance the cache strategy, etc.
http://webplatform.io / twitter @giorgionatili / Mc-Graw Hill Education
Thank you for your time. a!
Any question?

Mais conteúdo relacionado

Mais procurados

The Peanut Butter Cup of Web-dev: Plack and single page web apps
The Peanut Butter Cup of Web-dev: Plack and single page web appsThe Peanut Butter Cup of Web-dev: Plack and single page web apps
The Peanut Butter Cup of Web-dev: Plack and single page web apps
John Anderson
 

Mais procurados (20)

Real World Lessons in Progressive Web Application & Service Worker Caching
Real World Lessons in Progressive Web Application & Service Worker CachingReal World Lessons in Progressive Web Application & Service Worker Caching
Real World Lessons in Progressive Web Application & Service Worker Caching
 
PWA 應用 - 實現網站離線瀏覽
PWA 應用 - 實現網站離線瀏覽PWA 應用 - 實現網站離線瀏覽
PWA 應用 - 實現網站離線瀏覽
 
JQuery UK February 2015: Service Workers On Vacay
JQuery UK February 2015: Service Workers On VacayJQuery UK February 2015: Service Workers On Vacay
JQuery UK February 2015: Service Workers On Vacay
 
JQuery UK Service Workers Talk
JQuery UK Service Workers TalkJQuery UK Service Workers Talk
JQuery UK Service Workers Talk
 
Building a js widget
Building a js widgetBuilding a js widget
Building a js widget
 
ServiceWorker: New game changer is coming!
ServiceWorker: New game changer is coming!ServiceWorker: New game changer is coming!
ServiceWorker: New game changer is coming!
 
Service workers and the role they play in modern day web apps
Service workers and the role they play in modern day web appsService workers and the role they play in modern day web apps
Service workers and the role they play in modern day web apps
 
"Service Worker: Let Your Web App Feel Like a Native "
"Service Worker: Let Your Web App Feel Like a Native ""Service Worker: Let Your Web App Feel Like a Native "
"Service Worker: Let Your Web App Feel Like a Native "
 
Introduction to AJAX In WordPress
Introduction to AJAX In WordPressIntroduction to AJAX In WordPress
Introduction to AJAX In WordPress
 
JS Chicago Meetup 2/23/16 - Redux & Routes
JS Chicago Meetup 2/23/16 - Redux & RoutesJS Chicago Meetup 2/23/16 - Redux & Routes
JS Chicago Meetup 2/23/16 - Redux & Routes
 
Modern frontend development with VueJs
Modern frontend development with VueJsModern frontend development with VueJs
Modern frontend development with VueJs
 
The Peanut Butter Cup of Web-dev: Plack and single page web apps
The Peanut Butter Cup of Web-dev: Plack and single page web appsThe Peanut Butter Cup of Web-dev: Plack and single page web apps
The Peanut Butter Cup of Web-dev: Plack and single page web apps
 
Offline First with Service Worker
Offline First with Service WorkerOffline First with Service Worker
Offline First with Service Worker
 
Service worker: discover the next web game changer
Service worker: discover the next web game changerService worker: discover the next web game changer
Service worker: discover the next web game changer
 
The Art of AngularJS - DeRailed 2014
The Art of AngularJS - DeRailed 2014The Art of AngularJS - DeRailed 2014
The Art of AngularJS - DeRailed 2014
 
Building Offline Ready and Installable Web App
Building Offline Ready and Installable Web AppBuilding Offline Ready and Installable Web App
Building Offline Ready and Installable Web App
 
REST to JavaScript for Better Client-side Development
REST to JavaScript for Better Client-side DevelopmentREST to JavaScript for Better Client-side Development
REST to JavaScript for Better Client-side Development
 
Laravel 8 export data as excel file with example
Laravel 8 export data as excel file with exampleLaravel 8 export data as excel file with example
Laravel 8 export data as excel file with example
 
AngularJS Deep Dives (NYC GDG Apr 2013)
AngularJS Deep Dives (NYC GDG Apr 2013)AngularJS Deep Dives (NYC GDG Apr 2013)
AngularJS Deep Dives (NYC GDG Apr 2013)
 
PWA Roadshow Seoul - HTTPS
PWA Roadshow Seoul - HTTPSPWA Roadshow Seoul - HTTPS
PWA Roadshow Seoul - HTTPS
 

Destaque

Mobile benchmarking-and-profiling
Mobile benchmarking-and-profilingMobile benchmarking-and-profiling
Mobile benchmarking-and-profiling
Giorgio Natili
 
Making your washing machine talk with a power plant
Making your washing machine talk with a power plantMaking your washing machine talk with a power plant
Making your washing machine talk with a power plant
Matteo Collina
 

Destaque (10)

The Little Shop of TDD Horrors
The Little Shop of TDD HorrorsThe Little Shop of TDD Horrors
The Little Shop of TDD Horrors
 
Big data and mobile
Big data and mobileBig data and mobile
Big data and mobile
 
I beacon mobile_tea
I beacon mobile_teaI beacon mobile_tea
I beacon mobile_tea
 
Clear the UIViewController Mess
Clear the UIViewController MessClear the UIViewController Mess
Clear the UIViewController Mess
 
Ecma6 in 30 minutes
Ecma6 in 30 minutesEcma6 in 30 minutes
Ecma6 in 30 minutes
 
Test first
Test firstTest first
Test first
 
Mobile benchmarking-and-profiling
Mobile benchmarking-and-profilingMobile benchmarking-and-profiling
Mobile benchmarking-and-profiling
 
Android, getting started
Android, getting startedAndroid, getting started
Android, getting started
 
No. la sottile arte di trovare il tempo dove non esite - codemotion 2015
No. la sottile arte di trovare il tempo dove non esite - codemotion 2015No. la sottile arte di trovare il tempo dove non esite - codemotion 2015
No. la sottile arte di trovare il tempo dove non esite - codemotion 2015
 
Making your washing machine talk with a power plant
Making your washing machine talk with a power plantMaking your washing machine talk with a power plant
Making your washing machine talk with a power plant
 

Semelhante a Service worker API

Your last mile to SOA and Web 2.0- Lotus Expeditor for Devices - Eric MF Hsu,...
Your last mile to SOA and Web 2.0- Lotus Expeditor for Devices - Eric MF Hsu,...Your last mile to SOA and Web 2.0- Lotus Expeditor for Devices - Eric MF Hsu,...
Your last mile to SOA and Web 2.0- Lotus Expeditor for Devices - Eric MF Hsu,...
mfrancis
 
Real-world Dojo Mobile
Real-world Dojo MobileReal-world Dojo Mobile
Real-world Dojo Mobile
Andrew Ferrier
 
Was l iberty for java batch and jsr352
Was l iberty for java batch and jsr352Was l iberty for java batch and jsr352
Was l iberty for java batch and jsr352
sflynn073
 

Semelhante a Service worker API (20)

Service workers are your best friends
Service workers are your best friendsService workers are your best friends
Service workers are your best friends
 
Your last mile to SOA and Web 2.0- Lotus Expeditor for Devices - Eric MF Hsu,...
Your last mile to SOA and Web 2.0- Lotus Expeditor for Devices - Eric MF Hsu,...Your last mile to SOA and Web 2.0- Lotus Expeditor for Devices - Eric MF Hsu,...
Your last mile to SOA and Web 2.0- Lotus Expeditor for Devices - Eric MF Hsu,...
 
LATEST_TRENDS_IN_WEBSITE_DEVELOPMENT.pptx
LATEST_TRENDS_IN_WEBSITE_DEVELOPMENT.pptxLATEST_TRENDS_IN_WEBSITE_DEVELOPMENT.pptx
LATEST_TRENDS_IN_WEBSITE_DEVELOPMENT.pptx
 
Seattle bestpractices2010
Seattle bestpractices2010Seattle bestpractices2010
Seattle bestpractices2010
 
Quo vadis, JavaScript? Devday.pl keynote
Quo vadis, JavaScript? Devday.pl keynoteQuo vadis, JavaScript? Devday.pl keynote
Quo vadis, JavaScript? Devday.pl keynote
 
Real-world Dojo Mobile
Real-world Dojo MobileReal-world Dojo Mobile
Real-world Dojo Mobile
 
A year with progressive web apps! #DevConMU
A year with progressive web apps! #DevConMUA year with progressive web apps! #DevConMU
A year with progressive web apps! #DevConMU
 
Dreamweaver CS6, jQuery, PhoneGap, mobile design
Dreamweaver CS6, jQuery, PhoneGap, mobile designDreamweaver CS6, jQuery, PhoneGap, mobile design
Dreamweaver CS6, jQuery, PhoneGap, mobile design
 
Front End Development | Introduction
Front End Development | IntroductionFront End Development | Introduction
Front End Development | Introduction
 
Software Engineering 2014
Software Engineering 2014Software Engineering 2014
Software Engineering 2014
 
GWT Architectures and Lessons Learned (WJAX 2013)
GWT Architectures and Lessons Learned (WJAX 2013)GWT Architectures and Lessons Learned (WJAX 2013)
GWT Architectures and Lessons Learned (WJAX 2013)
 
Anatomy of an HTML 5 mobile web app
Anatomy of an HTML 5 mobile web app Anatomy of an HTML 5 mobile web app
Anatomy of an HTML 5 mobile web app
 
Krishnagopal Thogiti_Java
Krishnagopal Thogiti_JavaKrishnagopal Thogiti_Java
Krishnagopal Thogiti_Java
 
Hybrid mobile apps
Hybrid mobile appsHybrid mobile apps
Hybrid mobile apps
 
Javaland 2014 / GWT architectures and lessons learned
Javaland 2014 / GWT architectures and lessons learnedJavaland 2014 / GWT architectures and lessons learned
Javaland 2014 / GWT architectures and lessons learned
 
Project SpaceLock - Architecture & Design
Project SpaceLock - Architecture & DesignProject SpaceLock - Architecture & Design
Project SpaceLock - Architecture & Design
 
Teamwork Presentation
Teamwork PresentationTeamwork Presentation
Teamwork Presentation
 
Lesson learned from 3 years with hybrid apps
Lesson learned from 3 years with hybrid appsLesson learned from 3 years with hybrid apps
Lesson learned from 3 years with hybrid apps
 
Angular js mobile jsday 2014 - Verona 14 may
Angular js mobile   jsday 2014 - Verona 14 mayAngular js mobile   jsday 2014 - Verona 14 may
Angular js mobile jsday 2014 - Verona 14 may
 
Was l iberty for java batch and jsr352
Was l iberty for java batch and jsr352Was l iberty for java batch and jsr352
Was l iberty for java batch and jsr352
 

Mais de Giorgio Natili

The short path to ecma 6
The short path to ecma 6The short path to ecma 6
The short path to ecma 6
Giorgio Natili
 
WebRTC communication and wearable devices
WebRTC communication and wearable devicesWebRTC communication and wearable devices
WebRTC communication and wearable devices
Giorgio Natili
 
Multithreading development with workers
Multithreading development with workersMultithreading development with workers
Multithreading development with workers
Giorgio Natili
 
Undoable architectures
Undoable architecturesUndoable architectures
Undoable architectures
Giorgio Natili
 
WebRTC and Mobile Integration
WebRTC and Mobile IntegrationWebRTC and Mobile Integration
WebRTC and Mobile Integration
Giorgio Natili
 
Develop, test and debug cross platforms apps with PhoneGap
Develop, test and debug cross platforms apps with PhoneGapDevelop, test and debug cross platforms apps with PhoneGap
Develop, test and debug cross platforms apps with PhoneGap
Giorgio Natili
 

Mais de Giorgio Natili (13)

Driving Assistant Solutions with Android
Driving Assistant Solutions with AndroidDriving Assistant Solutions with Android
Driving Assistant Solutions with Android
 
Isomorphic Reactive Programming
Isomorphic Reactive ProgrammingIsomorphic Reactive Programming
Isomorphic Reactive Programming
 
The short path to ecma 6
The short path to ecma 6The short path to ecma 6
The short path to ecma 6
 
Jasmine 2.0
Jasmine 2.0Jasmine 2.0
Jasmine 2.0
 
Harmonik
HarmonikHarmonik
Harmonik
 
Mobile raspberry pi
Mobile raspberry piMobile raspberry pi
Mobile raspberry pi
 
WebRTC communication and wearable devices
WebRTC communication and wearable devicesWebRTC communication and wearable devices
WebRTC communication and wearable devices
 
Multithreading development with workers
Multithreading development with workersMultithreading development with workers
Multithreading development with workers
 
TDD and PhoneGap
TDD and PhoneGapTDD and PhoneGap
TDD and PhoneGap
 
Undoable architectures
Undoable architecturesUndoable architectures
Undoable architectures
 
Test first!
Test first!Test first!
Test first!
 
WebRTC and Mobile Integration
WebRTC and Mobile IntegrationWebRTC and Mobile Integration
WebRTC and Mobile Integration
 
Develop, test and debug cross platforms apps with PhoneGap
Develop, test and debug cross platforms apps with PhoneGapDevelop, test and debug cross platforms apps with PhoneGap
Develop, test and debug cross platforms apps with PhoneGap
 

Último

DeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakesDeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakes
MayuraD1
 
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments""Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
mphochane1998
 
Standard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayStandard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power Play
Epec Engineered Technologies
 
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 

Último (20)

Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...
Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...
Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...
 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . ppt
 
HOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptx
HOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptxHOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptx
HOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptx
 
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
COST-EFFETIVE  and Energy Efficient BUILDINGS ptxCOST-EFFETIVE  and Energy Efficient BUILDINGS ptx
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
 
2016EF22_0 solar project report rooftop projects
2016EF22_0 solar project report rooftop projects2016EF22_0 solar project report rooftop projects
2016EF22_0 solar project report rooftop projects
 
Hostel management system project report..pdf
Hostel management system project report..pdfHostel management system project report..pdf
Hostel management system project report..pdf
 
Engineering Drawing focus on projection of planes
Engineering Drawing focus on projection of planesEngineering Drawing focus on projection of planes
Engineering Drawing focus on projection of planes
 
DeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakesDeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakes
 
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptx
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptxA CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptx
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptx
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPT
 
Computer Lecture 01.pptxIntroduction to Computers
Computer Lecture 01.pptxIntroduction to ComputersComputer Lecture 01.pptxIntroduction to Computers
Computer Lecture 01.pptxIntroduction to Computers
 
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments""Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
 
Standard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayStandard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power Play
 
Rums floating Omkareshwar FSPV IM_16112021.pdf
Rums floating Omkareshwar FSPV IM_16112021.pdfRums floating Omkareshwar FSPV IM_16112021.pdf
Rums floating Omkareshwar FSPV IM_16112021.pdf
 
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
 
Design For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the startDesign For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the start
 
Learn the concepts of Thermodynamics on Magic Marks
Learn the concepts of Thermodynamics on Magic MarksLearn the concepts of Thermodynamics on Magic Marks
Learn the concepts of Thermodynamics on Magic Marks
 
Introduction to Serverless with AWS Lambda
Introduction to Serverless with AWS LambdaIntroduction to Serverless with AWS Lambda
Introduction to Serverless with AWS Lambda
 
Minimum and Maximum Modes of microprocessor 8086
Minimum and Maximum Modes of microprocessor 8086Minimum and Maximum Modes of microprocessor 8086
Minimum and Maximum Modes of microprocessor 8086
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - V
 

Service worker API

  • 1. JavaScript! ! Multithreading
 
 Everybody knows Javascript is single-threaded and that it shares this same thread with other browser-related processes such as painting and compositing. There are several techniques to implement pseudo multithreading in JavaScript; however, during this talk we will focus our attention on how to use and debug the Service Worker API. Our end goal is to explore practical use cases in order to simplify the process to render complex user interfaces and transitions in a browser. @giorgionatili
  • 2. Giorgio ! Natili! Lead of Mobile Engineering! ! Giorgio is an author, educator, community leader and Lead UI Engineer in McGraw Hill Education, a publisher of print and digital information services for the academic, professional and library markets. Giorgio was also the founder of GNStudio, a boutique Rome-based development and design studio specializing in engaging and accessible web and mobile experiences. A strong proponent of agile development practices, Giorgio's areas of expertise include standards-based application development, client-side scripting, gaming, and video streaming.
 ANDROID IOS (SWIFT) JAVASCRIPT CORDOVA TDD + BDD WEBRTC @giorgionatili
  • 4. We are hiring!!!
 Send your resume to: meirav@tegrity.com
  • 5. Today’s! Agenda Offline Web Application Why offline is not a failure, and why we should embrace offline scenarios as an opportunity. Service Workers Discover how a service worker works, understand the main gotchas to start with, and how to use the API today, especially in mobility. Multithreading Javascript Explore how to create even more scalable web apps using service workers and how to delegate networking and other expensive operations to “external” entities.
  • 8. Offline! WebApps ! is an Old! Topic • Occasionally connected computing literature dates back to the 1970s.
 • Macromedia tried to enable offline with Central 
 • A List Apart discussed these techniques in 2013
  • 9. Lack of Connectivity is not an Error • Don’t treat a lack of connectivity like an error.
 • Apps should be able to handle dropped connections. ! • Apps should keep minimal functionalities when offline.
  • 14. What is the most important capability shared between these devices?
  • 15. All of them can be offline!
  • 16. Offline is a New Opportunity • Designing apps and their interfaces for intermittent connectivity leads to an abundance of new scenarios and problems. ! • Solving all of them means that your app should preempting users’ needs.
  • 17. Review Your Architecture Separation Of Concerns Resource OptimizationData Request Flow In order to implement a successful offline strategy it’s mandatory to define clear boundaries between UI elements, logic and content. An app is nothing without data; however, a well organized data request flow can offer a good experience also in offline mode. Caching spaces are limited; optimizing images, CSS, JS files, etc. is a very important phase of the re-architecture. There isn’t an app that cannot be improved. Iterating in a collaborative way over and over is the preferred way to evolve architectures.! 
 However, bad architectures exist. Don’t be scared to start over embracing the “offline first” approach!
  • 18. Identify Clearly The App Layers 03. Bundles Optimizing the UI for different screens means also feeding the app with appropriately compressed images, this consideration is the key to avoid issues with caches size. 04. User Interface Be sure to decouple components as much as possible; otherwise caching the dependencies will proof difficult when implementing any strategy. 01. Communication Layer Use the fetch API and avoid implementing a call-back pyramid of doom; take advantage of the Promises and of their sequential syntax. 02. Network Layer Avoid a single bundle; breaking down the app in more than a single monolithic bundle will be the key for a layered caching strategy.
  • 19. Thinking! Offline! Native Experience Think to the offline re-architecture as an opportunity to handle your app as if it were a native one. Better Functionalities The reviewed architecture will help you to handle gracefully the points of failures (POF) of your app. Future Proof Handling remote requests with offline use in mind will help you to integrate the fetch API.
  • 21. Workers in a Nutshell Web Workers Web workers provide a simple means for web content to run scripts in background threads. The worker thread can perform tasks without interfering with the user interface.! Shared Workers A shared worker is a specific kind of worker that can be accessed from several browsing contexts, such as several windows, iFrames, or even workers (in the same domain). Service Workers Service workers are event-driven workers that act as proxy servers that sit between web applications, the browser, and the network (when available).
  • 22. A Quick Overview • The ServiceWorkers API allows us to make sites work offline through intercepting network requests and programmatically telling the browser what to do with these requests.
 • This API works in Chrome and other browsers (https://github.com/coonsta/ cache-polyfill) ! • chrome://inspect/#service-workers
  • 23. Features • The killer feature in the ServiceWorker API is the offline “first” nature.
 • A service worker is a background worker (easy multi-threading).
 • The API allows us to implement background sync, geofencing and network control.
  • 24. WebWorker! Lifecycle • On install (as a dependency or not)
 • On activate
 • On push message
 • On background-sync ! • On terminate
  • 25. Registering a ! Service! Worker let sw = navigator.serviceWorker;
 
 sw.register('service-worker.js', 
 {scope: './'}).then(function(registration) { ! // Handle the installation gracefully ! });
  • 26. self.addEventListener('install', function(event) { event.waitUntil( caches.open('static-v3').then(function(cache) { return cache.addAll([
 ! '/css/whatever-v3.css', '/css/img/sprites-v6.png', '/css/fonts/whatever-v8.woff', '/js/all-min-v4.js'
 ! // Whatever your app needs to run ! ]); }) ); }); Service Worker! Installation!
  • 27. Not Blocking! Installing self.addEventListener('install', function(event) { event.waitUntil( caches.open('assets-core-v1').then(function(cache) { cache.addAll( ! // Optional assets ); }) ); });
  • 28. Service Worker! Activation self.addEventListener('activate', function(event) { event.waitUntil( caches.keys().then(function(cacheNames) { return Promise.all([ ! // It happens when the page reload or // when a new version is installed // It’s the best place to manage the caches ]); }) ); });
  • 29. Service Worker! Fetch self.addEventListener('fetch', function(event) { event.respondWith( caches.match(event.request).then(function(response) { // Return network with cache fallback // Basic, CORS or Opaque responses return response || fetch(event.request); }) ); });
  • 30. Service Worker! Notification self.addEventListener('push', function(event) { if (event.data.text() == 'new-tweet') { ! // Handle caches and prepare the content for the view ! }}); ! self.addEventListener('notificationclick', function(event) { if (event.notification.tag == 'new-tweet') { ! // Assume that all of the resources needed to render // the 'inbox' have previously been cached ! new TweetView('inbox'); } });
  • 31. Service Worker! Background Sync self.addEventListener('sync', function(event) { if (event.id == 'update-leaderboard') {
 // Or whatever promise that sync the data return openBgSyncDB(); });
  • 32. Security! ! During development you'll be able to use service worker through localhost; however, to deploy it on a site, you'll need to set up HTTPS on your server.
  • 33. No Extra! Tests • A ServiceWorker returns eventually cached results.! • Emulating offline the tests previously written should fulfill without any extra effort.
  • 34. Debugging! ! You can debug a service worker with the standard Chrome DevTools ! (Note: debug in an incognito window)
  • 36. Browsers Support (I am really confident about IE!) // Include SW cache polyfill importScripts("js/serviceworker-cache-polyfill.js");
  • 37. Size! Matters • Your origin is given a certain amount of free space to use as it sees fit. ! • That free space is shared between all origin storage: LocalStorage, IndexedDB, Filesystem, and Caches. ! • The amount you get isn't specified; it will differ depending on device and storage conditions.
  • 39. JavaScript ! is ! Multithread • Tasks are scheduled so the browser can get from its internals into JavaScript/DOM land and ensures these actions happen sequentially. Between tasks, the browser may render updates.! ! • Microtasks are usually scheduled for things that should happen straight after the currently executing script, such as reacting to a batch of actions, or to make something async without taking the penalty of a whole new task
  • 42. Web & Shared Workers Scenarios! • Image processing! • Large amount of data recovery! • Text analysis ! • Complex algorithms (e.g. adaptive learning)! • Game engines! • Angular digest cycle (why not ?!?)
  • 43. Service Workers Scenarios ! • Offline applications! • Performance improvement! • Notifications! • Background updating
  • 44. 01. 02. 03. 04. Workers! Based! Architecture 03. Service Workers Delegate to the Workers process intensive operations such as data parsing and massaging, expensive network request, etc. 04. Web & Shared Workers Split the business logic in self-contained components to help reduce dependencies; eventually bundle together layers of the app when it’s too complicated to reduce the dependencies. 01. Business Logic Create a communication bridge between components! and the worker layers using events and the! postMessage API. 02. Communication Layer Use the Service Worker(s) to handle the cache of the shell needed to render the app also in offline mode.
  • 45. Useful Links and Resources • The offline cookbook https://jakearchibald.com/2014/offline-cookbook/! • The fetch() API https://developers.google.com/web/updates/2015/03/introduction-to-fetch?hl=en! • Designing offline first apps http://alistapart.com/article/offline-first! • Using WebWorker with Angular https://andywalpole.me/#!/blog/142677/using-web-workers-angularjs! • A simple ServiceWorker app http://blog.lamplightdev.com/2015/01/06/A-Simple-ServiceWorker-App/ ! • Introduction to ServiceWorker http://www.html5rocks.com/en/tutorials/service-worker/introduction/! • Progressive networking https://ponyfoo.com/articles/progressive-networking-serviceworker! • ServiceWorker explained https://github.com/slightlyoff/ServiceWorker/blob/master/explainer.md ! • Application shell architecture https://medium.com/google-developers/instant-loading-web-apps-with-an-application-shell- architecture-7c0c2f10c73#.9ld0u2liz ! • Sending an app to the browser https://surge.sh/! • Hoodie use case http://hood.ie/blog/minutes-offline-case-study.html
  • 46. Offline 
 First! Summary! Review Code, Design & Content Clearly identify code responsibilities, decouple code from design, define the boundaries between content and UI, etc. Refactor & Enhance Code Clean the code, decouple components from each other, expose clear APIs, take advantage of Promises, etc. Handle Network Failure Determine what the app needs to run without network connection, handle the use cases in Workers, progressively enhance the cache strategy, etc.
  • 47. http://webplatform.io / twitter @giorgionatili / Mc-Graw Hill Education Thank you for your time. a! Any question?