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
  begin
    navigator.serviceWorker.register('sw-v1.js')
      .then(procedure(registration:variant)
      begin
        console.log('Service Worker registered with scope: ', registration.scope);
      end)
      .catch(procedure(err:variant)
      begin
        console.log('Service worker registration failed: ', err);
      end)
  end;

(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
    event.respondWith(
        fetch("res/appmodified.css");
      )
    );
  end
end);

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 

    asm
    event.respondWith(
      new Response(
        "body {background: green !important;}",
        {headers: {"Content-Type": "text/css" }}
      )
    );
    end;

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
  https://www.quora.com/Whats-the-difference-between-service-workers-and-web-workers-in-JavaScript
  https://stackoverflow.com/questions/38632723/what-can-service-workers-do-that-web-workers-cannot

using serviceWorkers
  https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers
  https://itnext.io/service-workers-your-first-step-towards-progressive-web-apps-pwa-e4e11d1a2e85
  https://developers.google.com/web/fundamentals/primers/service-workers/

inline webworker file
  https://forums.smartmobilestudio.com/topic/4662-compiled-procedures/?tab=comments#comment-23272

URL.createObjectURL not for serviceWorkers
  https://www.chromestatus.com/feature/5685092332601344
  https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL
  https://github.com/w3c/ServiceWorker/issues/688
Failed to register a ServiceWorker: The URL protocol of the script ('blob:http%3A//127.0.0.1%3A8090/ac72036e-ed81-49d7-9202-f0323e2018fe') is not supported.

workertest : test your browser
  https://html5workertest.com/

cookbook
  https://serviceworke.rs/

google
  https://developers.google.com/web/fundamentals/codelabs/your-first-pwapp/
  (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.

Guest
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...