Making Service Specialcan bet: A Case Study


there can be no shortage of boostercan bem or excthe itemement about the fledgling API service factor , can be right now shipping in some common browsers. There are cookbooks in addthe itemion to blog posts, code snippets in addthe itemion to tools. But I find in which when I want to learn a bras well as-new concept on the Internet completely, rolling up my sleeves ideals, in addthe itemion to diving in in addthe itemion to build something by scratch can be often ideal.

in addthe itemion to bumps in addthe itemion to brucan bees, gotchas in addthe itemion to bugs I ran into thcan be time has benefthe items: Now I understin addthe itemion to much better service workers, in addthe itemion to wthe itemh any luck I can help you avoid some of the headaches faced when working wthe itemh a bras well as-new API

Service workers do a lot of different things ; there are ways countless to harness their powers. I decided to build a simple service to my agent (fixed, non-complex) sthe iteme in which reflects almost Features outdated storage API application temporary user to provide - in addthe itemion to in which can be:

    [194503million] make the job sthe iteme can be currently, [194503million] increase internet performance by reducing network requests for certain assets,
  • currently provides customized experience decline.

before the start, I could like to pay trineverthelesse to two people who work to make thcan be possible. First of all, I owe largely to Jeremy Kethe itemh for the implementation of service workers on the items own, which served as a starting point for my code. It was a source of inspiration to me office recently , describing hcan be current experiences of service factor. In fact, my work can be so derivative debt in which I had not wrthe itemten about the item except for the sermon Jeremy in previous job :

even if, please decided to play around wthe itemh workers service, please share your experience .

Second, all kinds of old big thanks to Jake Archibald for review excellent technical in addthe itemion to reactions. Always wonderful when one of the service factor specifications 's creators, evangelcan bets able to fthe item you!

What can be the service factor anyway? link

Service factor can be text in which stin addthe itemion tos between your web sthe iteme in addthe itemion to network , allowing you to, among different things, the abilthe itemy to intercept network requests in addthe itemion to answer ways different

for the sake of your Web sthe iteme or application to work, in addthe itemion to the browser brings the items assets - such as HTML pages in addthe itemion to JavaScript, images, fonts. In the past, thcan be admincan betration was right on top of the browser. If the browser can not access the network, you are likely to see her, "Hey, you're offline" message. There were methods in which you can use to encourage local cache of assets, nevertheless often the browser final say.

Thcan be was not such a great experience for users who are currently, in addthe itemion to the item left web developers wthe itemh lthe itemtle control over the browser cache.

cue cache application (or AppCache), which a few years ago looked promcan being on arrival. It allows you ostensibly dictates how various assets should be dealt wthe itemh, to ensure your Web sthe iteme or application can be done offline. After lied inter simple AppCache appearance of underlying confusion of nature in addthe itemion to the lack of flexibilthe itemy .

API nascent service worker can do what he did AppCache, a whole lot more. But the item seems a bthe item daunting at first. Specifications make heavy in addthe itemion to abstract to read, in addthe itemion to programming interfaces numerous applications are affiliated or related: cache , bring , etc. service workers a lot of functions include: push notifications, in addthe itemion to soon, background synchronization. Compared AppCache, the item seems ... complex.

while AppCache (which, by the way, can be goes away ) the item was easy to learn, nevertheless terrible for every single moment after in which (my opinion) in addthe itemion to service workers are more inthe itemial investment of kright nowledge, nevertheless they are powerful in addthe itemion to useful, in addthe itemion to usually you can get yourself out of trouble if you break things.

some basic concepts Agent Service link

Service factor can be a file wthe itemh some JavaScript inside item. In thcan be file you can JavaScript wrthe iteming as you kright now in addthe itemion to love, wthe itemh a few important things you should keep in mind.

manuscripts Agent service operates in a separate thread inside browser by the pages they control. There are ways of communication between workers in addthe itemion to pages, nevertheless inside implementation of separate the scope of . Thcan be means you will not have access to the DOM of those pages, for example. I imagine the service worker as a kind of works in a separate tab on the page because the item affects. Thcan be can be not at all accurate, nevertheless the item can be a useful metaphor crude to keep myself by confusion.

JavaScript in your service worker must not be blocked. You need to use APIs asynchronously. For example, you can not use localStorage inside service factor ( localStorage API can be synchronous). Humorously enough, even wthe itemh thcan be kright nowledge, I managed to run the rcan bek of violation, as we shall see.

recording agent service link

make you effective agent service before the item can be regcan betered. Thcan be recording can be by outside the service factor, through as well asifferent page or text on your web sthe iteme. On my web sthe iteme, which can be a global company sthe iteme.js text in every HTML page can be included. Place on record my service worker by there.

when recording service worker, (optionally) also say in which what domain should apply the itemself. You can instruct the service factor only to deal wthe itemh the stuff of a part of your web sthe iteme (for example, '/ blog /' ), or you can regcan beter the item to your web sthe iteme whole ( '/' ) as I do.

life service workers cycle in addthe itemion to events link

Service can be doing the bulk of the work factor lcan betening to the events related to in addthe itemion to respond to the useful ways . Various events are run at various points inside life cycle of service factor.

once have been downloaded factor services in addthe itemion to recording, the item gets install inside background. Service factor can lcan beten to install event in addthe itemion to perform appropriate tasks for thcan be stage.

In our case, we want to take advantage of install State to the pre--cache group of assets in which we kright now we will want wthe itemhout contact at a later time.

after fincan behed installing stage, in addthe itemion to then the service factor activated . Thcan be means in which the service workers right now in control of matters wthe itemhinside scope of domain can do everything. And activation event can be not very excthe iteming factor for the bras well as-new service, nevertheless we'll see how the item's useful when updating service worker wthe itemh the bras well as-new type.

exactly when activated happens depends on whether thcan be can be a brin addthe itemion to bras well as-new service agent or an updated type of the service factor excan beted before. If the browser does not have an earlier type of a particular service can be already regcan betered agent, in addthe itemion to activation occurs immediately after the installation can be complete.

Once installed full activation, in addthe itemion to the item will not occur again until the updated type of the service can be loaded in addthe itemion to regcan betered agent.

after the installation in addthe itemion to activation, in addthe itemion to we will be looking primarily at the bring happened today to make the factor we have a useful service. But there are many useful activthe itemies beyond in which: sync events in addthe itemion to notification events, for example

to get extra credthe item or entertainment in addthe itemion to fun, you can read more about [ interfaces in which service workers implementation of . It can be through the implementation of these interfaces in which the service workers to get the bulk of these events in addthe itemion to a lot of long in addthe itemion to functions.

API based on the promcan bee of service workers link

in addthe itemion to factor API service makes extensive use of promcan bees . It represents the promcan bee of the final outcome of the process can be out of sync, even if the actual value will not be kright nown until the process can be completed some time inside future.

  getAnAnswerToADifficultQuestionSomewhereFarAway (). Then (answer => console.log (`got the answer on the $ `!);) .catch (Mind => console.log (`tried to learn the item nevertheless could not because the $ reason '); );  

in addthe itemion to getAnAnswer ... function returns promcan beed in which (wishfully) will eventually be fulfilled by, or solution to, in addthe itemion to answer we are looking for. After in which, the answer can feed any chained then functions processor, or, inside case of the appalling failure to achieve hcan be goal, in addthe itemion to promcan beed could be rejected - often wthe itemh reason - in addthe itemion to catch functions processor can take care of these cases

There are more than promcan bees, nevertheless I'll try to keep the examples here directly (or at least suspended.). I urge you to do some information reading If you are bras well as-new to the promcan bees of

Note : I use certain ECMAScript6 (or ES2015) features inside code sample service workers for because of browsers support service workers also supports these features. Specifically here, in addthe itemion to I am using functions arrow in addthe itemion to template chains .

necessthe itemies as well asifferent factor Service link

Note alto ensure the service workers requires HTTPS to work. There can be an important in addthe itemion to useful exception to thcan be rule: service workers working for local host unsafe HTTP , which can be a source of satcan befaction for the establcan behment of local SSL in some cases fag

fact enjoyable : Thcan be project forced me to do something I had been delayed for some time: to obtain in addthe itemion to configure for SSL www subtype of my websthe iteme. Thcan be can be something I could urge people to consider doing because pretty much all of the bras well as-new fun stuff to reach the browser inside future will require SSL to be used.

we will put all things work together today in Chrome (I use type 47). Any day right now, Firefox 44 in addthe itemion to the ship, in addthe itemion to the item supports the workers inside area of ​​services. Do service workers ready? provides accurate information on the support in different browsers.

recording, installation in addthe itemion to activation of service workers link

in addthe itemion to right now we 'I have taken care of some theory, we can start assembling our service worker.

to install in addthe itemion to activate the service factor, in addthe itemion to we want to lcan beten to install in addthe itemion to activation events in addthe itemion to act on them.

we can start wthe itemh a blank factor for our services file in addthe itemion to add a few eventLcan beteners . In serviceWorker.js :

  self.addEventLcan betener ('install', the event => // Do stuff install); self.addEventLcan betener ('activation', the event = > // Do activating stuff: Thcan be will come at a later time);  

recording our workers Service link

Now we need to tell the pages on our Internet to use the service factor.

Remember, thcan be recording can be happening outside of the service factor - in my case, by wthe itemhin a script ( /js/sthe iteme.js ), which can be included on each page of my sthe iteme

in my [ sthe iteme.js :

  if ('serviceWorker "inside navigator) navigator.serviceWorker.regcan beter (' / serviceWorker.js',  scale : '/');  

before a fixed spool assets through the installation of link

I want to use to install the pre-cache some of the assets on the Web sthe iteme my.

  • the pre-caching of some fixed assets (images, CSS in addthe itemion to JavaScript) in which can be used by many of the pages on my websthe iteme, I can speed up downloads by grabbing Thcan be by the cache, instead of bringing the network load on the subsequent page.
  • by Page decline offline caching before, in addthe itemion to I can pretty page appears when I can not fulfill the request page because the user can be offline.

in addthe itemion to steps to do so are:

  1. Tell the install event to hang on in addthe itemion to not complete until I've done what I can do using event. wathe itemUntil .
  2. open appropriate cache , clinging to fixed assets in using Cache.addAll . In gradual application on the Internet language, these assets make up my "application shell."

in /serviceWorker.js , let's expin addthe itemion to in addthe itemion to install processor:

  self.addEventLcan betener ('install', Event => function onInstall () return ('fixed'). Then (cache => cache.addAll (['/images/lyza.gif', '/js/sthe iteme.js',' / css /styles.css', '/ offline /', '/'])); event.wathe itemUntil (onInstall (event)););  

in addthe itemion to service factor can be applied CacheStorage interface , which makes the item caches globally available property in our service worker. There are several useful ways for caches - for example, open in addthe itemion to delete

you can see promcan bees at work here: returns promcan beed solution for cache object once the item opened successfully fixed cache. addAll also returns promcan beed in which each of the the itemems in which are passed to the item has been hidden inside cache solves.

say thcan be event wathe item until the solution promcan beed returned by my hin addthe itemion toler function successfully. Then we can be sure in which all of these the itemems before the cache get ranked before the installation can be complete.

console jamming link

cliche recording link

probably can be not wrong, nevertheless certainly confusion : If you console.log working inside field of services, Chrome will continue to re-dcan beplay (rather than clear) those messages log on subsequent page requests. Thcan be makes seems events such as firing often or similar executing code over in addthe itemion to over again.

For example, let's add Regcan beter permthe item our install processor:

  self.addEventLcan betener ('install', the event => // ... as before console.log ('install'););  
Stale Logs Freak Me Out
as of Chrome 47 , will continue to "install" message can be logged to appear on a subsequent page requests. Chrome can be not truly a shot of install event on each page load. Instead, the item appears the records in which have no meaning. ( send large copy )
[194509million] error when things are OK link

can be in which once something else strange in addthe itemion to activated service can be installed factor , load the subsequent page to any page wthe itemhinside scope always causes one error inside console . I thought I was doing something wrong.

Omnimpresent Chrome Service Worker Error
as of Chrome 47, access to the page wthe itemh the Agent service can be already regcan betered will always cause thcan be error on the console. ( send large copy )

what we have achieved so far link

in addthe itemion to agent service addresses install event before caches -Some of fixed assets. If you were to use thcan be service worker in addthe itemion to regcan betered, before the item hideout in fact the assets referred to, nevertheless will not be able to take advantage after them right now.

contents serviceWorker.js are on Gthe itemHub .

Fetch deal wthe itemh service workers link

so far, our service incorporates a worker-fleshed install processor nevertheless do not do any anything beyond in which. The charm of our service factor alone truly happen when bring events are run.

we can respond in different ways to bring in. Using a different network strategies , in addthe itemion to we can tells the browser to always try to bring some of the assets of the network (the main content certainly makes the item bras well as-new), while prefer copies hidden fixed assets - slimming truly down payloads our page. We can also provide offline nice to retreat if all else fails.

whenever a browser wants to bring the assets wthe itemhinside service thcan be factor, we can hear about the item before, yes, in addthe itemion eventLcan betener in serviceWorker.js :

  self.addEventLcan betener ('fetch', the event => // ... respond Maybe in which's brought in a useful way?);  

again, bring all in which fall wthe itemhinside scope of thcan be service for workers (ie path) will lead thcan be event - HTML pages, scripts, images, CSS, you name the item. We can hin addthe itemion tole the road selectively browser responds to any of these bring.

we should deal wthe itemh thcan be Fetch? link

when bring happen out of the event, the first thing I want to determine can be whether thcan be service worker should interfere wthe itemh the fetch of a particular resource. Otherwcan bee, you must do nothing in addthe itemion to let the browser assert the items default behavior

in addthe itemion to we will end up wthe itemh the basic logic such as thcan be in serviceWorker.js :

  self.addEventLcan betener ('fetch', the event => function shouldHin addthe itemion toleFetch (event, chooses) // We must deal wthe itemh thcan be fetch function onFetch (event, chooses) // ... TBD: Response to bring if ( shouldHin addthe itemion toleFetch (event, configuration)) onFetch (event, configuration););  

in addthe itemion to shouldHin addthe itemion toleFetch function evaluates a specific request to determine whether to provide a response, or let the browser assert default deal.

Why not use promcan bees? link

to maintain wthe itemh a penchant service worker promcan bees, the first type of my bring appeared event hin addthe itemion toler like thcan be:

  self .addEventLcan betener ( 'fetch', the event => function shouldHin addthe itemion toleFetch (event, chooses)  function onFetch (event, chooses)  shouldHin addthe itemion toleFetch (event configuration). Then (onFetch (event, configuration)) .catch (...); );  

seems logical, nevertheless I made a couple of rookie mcan betakes wthe itemh promcan bees. I swear I did not even feel the smell of code at the beginning, nevertheless the item was Jake who put me straight on the percussive errors. (Lesson: As can be always the case, if the code feels wrong, the item probably can be.)

refused to promcan bee should not be used to refer, instead, must refusal indicate, "" I got the answer I did not like. "Oh, crap, something goes wrong in an attempt to get the answer." That can be, rejection must be exceptional .

stkthe itemards require valid link

right, back to determine whether a particular request applies to bring my service agent. My sthe iteme-specific crthe itemeria are as follows:

  1. in addthe itemion to requested URL should represent something I want to store or post. Path must match wthe itemh regular expression by the correct paths.
  2. should be the HTTP method for the request get .
  3. should be asked to get out of my resources ( ).

If any of stkthe itemards tests for false , we should not be dealing wthe itemh thcan be application. In serviceWorker.js :

  function shouldHin addthe itemion toleFetch (event, chooses) {var request = event.request. Var URL = URL of the bras well as-new (request.url); var crthe itemeria = matchesPathPattern: !! (opts.cachePathPattern.exec (url.pathname), can beGETRequest: request.method === 'GET', can beFromMyOrigin: url.origin === self.location.origin; // create only a bras well as-new set of keys wthe itemh stkthe itemards /^/(?:(20[0-9]2|about|blog|css|images|js)/(.+)?)?$/ /^/(?:(20[0-9]2|about|blog|css|images|js)/(.+)?)?$/
http://cheapestdigthe Service Specialcan bet: A Case Study : Making Service Specialcan bet: A Case Study
Share on Google Plus

0 Response to " Making Service Specialcan bet: A Case Study "

Post a Comment