Jump to content

serviceWorkers (fetch)

Recommended Posts

  • Moderators

WebWorkers are a way of off-loading tasks from the main browser into a separate thread. ServiceWorkers sit between the browser and the network and extend these capabilities by a couple of powerful features :

  • offline detection and interception possibilities of network requests (fetch api)
  • resource caching under program control (new cacheStorage api)
  • background syncing
  • saving browser apps as icons on the homescreen
  • serving push notifications

ServiceWorkers are integral to Progressive Web Apps

Architecturally a serviceWorker is just a separate js file, which means that 2 Smart projects are needed (one for the main program, one for the serviceWorker). For normal webWorkers there is a workaround in that it is possible to generate an in-memory js-file using the blob: protocol (see forum post here), so the webWorker can be generated from the main program. For serviceWorkers this approach should work as well, however all modern browsers have closed this avenue (see here, here and here). Not sure if this is temporary or permanent.

ServiceWorkers are created in the main program, a bit differently then normal. No 'new' object constructor but instead a call to a registration function, returning a promise.

  var navigator external 'navigator': variant;

  if navigator.serviceWorker then
        console.log('Service Worker registered with scope: ', registration.scope);
        console.log('Service worker registration failed: ', err);

(Adding the link to the external navigator object in the first line means no asm blocks are required. The above could be wrapped up in a TServiceWorker object).


1) network request interceptions (fetch)

For the serviceworker : start a new project and delete all pre-generated forms and units. Set output to js file (linker) and unclick 'use main body' in code generation. Replace contents of root-unit with

var sw : variant;
asm @sw = self; end;

sw.addEventListener("fetch", procedure(event:variant) begin
  if (event.request.url.includes("res/app.css")) then begin

Soon as the request to load the standard Smart resource-file 'res/app.css' is detected, it is intercepted and replaced with another resourcefile.

Usually communication between worker and main is done through messaging. There is however a short-cut where the worker can modify the calling main page directly : add a Response object to the event.responseWith method with appropriate headers 

      new Response(
        "body {background: green !important;}",
        {headers: {"Content-Type": "text/css" }}

this will change the backgroundcolor of the form to green. Change the Content-Type to "text/html" and the preceding string to valid html and the form will be replaced with the rendered html content.

demo (click button and do refresh) and projects (main and worker)


Link to post
Share on other sites
  • Moderators

Technically the cacheStorage api is not that hard, but choosing and implementing the different scenario's (cache-first-then-network, network-first-then-cache etc etc) becomes a bit tedious. And then there is the old browser caching mechanism too, which doesn't go away - two different caching mechanisms to take care of.

There is a caching cookbook below (and some other links I collected for myself)

difference between webworkers and service workers

using serviceWorkers

inline webworker file

URL.createObjectURL not for serviceWorkers
Failed to register a ServiceWorker: The URL protocol of the script ('blob:http%3A//') is not supported.

workertest : test your browser


  (problems : yahoos weather service is deprecated as per jan 2019 - converting it to OpenWeatherMap
              sourcecode insists unnecessarily on installing everything in server root - changed urls of resources to relative)


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Create New...