It’s just data

Service Workers - First Impressions

Created by potrace 1.13, written by Peter Selinger 2001-2015

Successes, progress, and stumbling blocks encountered while exploring Service Workers.


The Apache Whimsy Board Agenda tool is designed to make ASF Board meetings run more smoothly. It does this by downloading all of the provided reports and collating them with comments, prior comments, action items, minutes, links to prior reports, links to committee information, and the like. It provides a UI to allow Directors and guests to enter comments. It provides a UI to allow the Secretary to take minutes.

The tool itself is built using React.JS. It starts by downloading all of the reports. Navigation between reports can be done via mouse clicks or cursor keys and doesn't involve any server interaction. As new data is received, the window is updated.

Finally, I'm new to Service Workers so I may be doing things in a profoundly dumb way. Any pointers would be appreciated. I am capable of RTFM and following examples.

First step - caching JSON

Some of the data (e.g., the list of ASF JIRA projects) is fetched on demand. Generally the page is first rendered using an empty list, and then updated once the actual list is received.

This process could be improved by caching the results received and using that data until fresh data arrives. As the Cache API is built on promises, and therefore asynchronous, this generally means rendering three times: once with a empty list, then with the cache, and finally with live data.

// retrieve an cached object.  Note: block may be dispatched twice,
// once with slightly stale data and once with current data
// Note: caches only work currently on Firefox and Chrome.  All
// other browsers fall back to XMLHttpRequest (AJAX).
JSONStorage.fetch = function(name, block) {
  if (typeof fetch !== 'undefined' && typeof caches !== 'undefined' && 
     (location.protocol == "https:" || location.hostname == "localhost")) {"board/agenda").then(function(cache) {
      var fetched = null;

      // construct arguments to fetch
      var args = {
        method: "get",
        credentials: "include",
        headers: {Accept: "application/json"}

      // dispatch request
      fetch("../json/" + name, args).then(function(response) {
        cache.put(name, response.clone());

        response.json().then(function(json) {
          if (!fetched || JSON.stringify(fetched) != JSON.stringify(json)) {
            if (!fetched) clock_counter--;
            fetched = json;
            if (json) block(json);

      // check cache
      cache.match(name).then(function(response) {
        if (response && !fetched) {
          response.json().then(function(json) {
            fetched = json;
            if (json) block(json);
  } else if (typeof XMLHttpRequest !== 'undefined') {
    // retrieve from the network only
    retrieve(name, "json", function(item) {return item.block})

All in all remarkably painless and completely transparent to the calling application. Doesn't involve the activation of Service Workers, but it doesn't have to.

Second step - caching HTML

What's true for JSON should also be true for HTML. Prior to the caching logic introduced above, and continuing to be true for browsers that don't support the service workers caching interface, data that should appear on the page would be missing briefly and show up a second or two later. In the case of HTML, that data would be the entire page. This would typically be seen both on the initial page load as well as any time a link is opened in a new tab.

The HTML case is both simpler and more difficult. Fetching the HTML from cache and then replacing it wholesale from the network, while possible, would be jarring. Fortunately, there already is logic in place to update the content of the pages based on updates received by XHR. So initially displaying where the user last left off, as well as updating the cache, is sufficient.

Unfortunately, it isn't quite so simple. I've included the current code below complete with log statements and dead ends.

// simple hashcode to prevent authorization from leaking
var hashcode = function(s) {
  return s && s.split("").reduce(
    function(a, b) {
      return ((a << 5) - a) + b.charCodeAt(0)


var status = {auth: null};

this.addEventListener("fetch", function(event) {
  var scope = this.registration.scope;
  var url = event.request.url;
  var path = url.slice(scope.length);
  var auth = hashcode(event.request.headers.get("Authorization"));

  if (/^\d\d\d\d-\d\d-\d\d//.test(path) && event.request.method == "GET") {
    console.log("Handling fetch event for", event.request.url);

    event.respondWith("board/agenda").then(function(cache) {
      return cache.match(path).then(function(cached) {
        if (cached) console.log("matched");
        console.log("auth", auth, status.auth);

        if (!auth || auth != status.auth) {
          // the following doesn't work
          cached = new Response("Unauthorized", {
            status: 401,
            statusText: "Unauthorized",
            headers: {"WWW-Authenticate": "Basic realm="ASF Members and Officers""}

          // fallback: ignore cache unless authorized
          cached = null

        if (cached) console.log("serving from cache");

        var network = fetch(event.request).then(function(response) {
          if (!cached) console.log("fetching from network");
          if (cached) console.log("updating cache");
          if (response.ok) cache.put(path, response.clone());
          status.auth = auth;
          return response

        return cached || network
  } else if (auth) {
    // capture authorization from other pages, if provided
    status.auth = auth

The primary problem is that the board agenda tool requires authentication to use as the data presented may contain Apache Software Foundation confidential information.

Without accounting for this, what often would be placed into the cache would be the HTTP 401 challenge response. That's not desirable.

Attempting to force the return of a challenge when an Authorization header is not present results in the display of the challenge response. Again, not what we want.

Falling back to only providing the cached data when the Authorization header is present (and matches the one used for the cache) results in the cache being used sometimes with Firefox. And, unfortunately, never with Chrome.

A secondary problem, of lesser importance, is that the cache never gets updated if the service worker responds with a cache copy. Of if it does, the console.log messages aren't getting executed or aren't producing output.

Third step - monitoring

To help with debugging, it occurred to me that it would make sense to produce a page that shows Service Worker and Cache status.


One thing I haven't explored yet is replacing the fetch call with one with different values for the request mode and credentials mode. I figured I would ask for guidance before proceeding down that path.

Once caching HTML is mastered, caching related artifacts like stylesheets and javascripts would be in order. An online fallfack approach would likely be the best match.

After that, the next order of business would be queuing of updates while offline. While in general, that would be a hard problem, in this case as user operations are limited by role and generaally to editing their own changes, it should be manageable.

The Student Room has the best writer for you in Australia to provide assignment help.Contact us today for instant writing services & get delivery before the submission date.

Posted by Myassignmenthelp at

Thanks For Sharing your information.

Posted by High Profile Escorts In Bangalore at

This is great information for students. This article is very helpful i really like this blog thanks. I also have some information relevant for online dissertation help.

Posted by Help With Programming Homework at

Well thanks for posting such an outstanding idea. I like this blog & I like the topic and thinking of making it right.

Posted by Electronics Engineering Homework Help at

I’ve been searching about this tools, gladly now I can make something out of it. Thanks for the share.

Posted by Mobile application Development Company at

The Student Room has the best author for you in Australia to give task help.Contact us today to moment composing administrations and get conveyance before the accommodation date.

Posted by Homework Writing Service at

service worker provide the service of the customer if your service is not good and your customer do not satisfied from your service so your customer will not again take the  service so your service is the first impression for your service in front of the customer.

Posted by service registration corrupt at

Great work

Posted by gapps download at

Ruchita Sinha provides top quality and best escorts in Pune. Pune Escorts services like independent escorts, high profile escorts, vip escorts in Pune, models and housewife. These hot and provocative escorts are available 24/7.

Posted by Ruchita Sinha at

Things Are Very Open And Intensely Clear Explanation Of Issues. Was Truly Information. Your Website Is Very Beneficial. MBA Assignment Help

Posted by MBA Assignment Help at

I’m Really Impressed With Your Article, Such Great & Usefull Knowledge You Mentioned Here Case Studies Analysis

Posted by Case Studies Analysis at

Calendar 2018 march for students

Posted by vav viv at

Cash Advance terms are generally straightforward.Cash Advance ChicagoAuto Title Loans ChicagoPayday Loans Chula-vistaCash Advance Corona

Posted by cash advance corona at

Check your cell phone and browse your email account. You will unquestionably observe the distinction. Tarjetas De Cumpleaños Feliz

Posted by aftab ali at

Check your cell phone and browse your email account. You will unquestionably observe the distinction. Tarjetas De Cumpleaños Feliz

Posted by aftab ali at

Be wary of people that solely translate a manuscript.

Posted by shoes in stock at

Take a look here for all the latest technological news from all over the globe

Posted by tekinancereporter at

hey guys if you are a roblox player then must try my link to get lots of robux for free

Posted by get free robux at

All the details are in this post is awesome

Posted by leona at

Facetime is the best video calling application for smartphones. In Facetime Apk, you can make both video and audio calls via Wifi or mobile network. Facetime Apk has its best alternative free video calls and chat app which allows you to do free video chat.

Posted by facetime app download at

Interesting topic shown here, i am now working on it regularly here and would say keep the future posts like this continuously.

Posted by 200-310 practice tests at

Great article

Posted by blanche at

A debt of gratitude is in order for sharing such a decent article and for educational things. Your articles are extremely stunning and I got a considerable measure of data and direction understanding them. It helped me a considerable measure and I will without a doubt take after your article strategies. Sitting tight for more valuable updates and new things

Posted by essay writing services UK at

Really great

Posted by london at

I think it is very interesting

Posted by monica at

Indeed, the squandering of time and showing untruthfulness in the arrangements can really hurt the esteem. olymptrade

Posted by aftab ali at

we have the best betting platform for you. Just come to our website, signup and get your bonus amount
online casino Singapore
Singapore online casino
mobile casino singapore
singapore 4D results
Singapore 4d results
4D results
Malaysia 4D results
Singapore betting tips
online Sportsbook Singapore
online Singapore online casino 2018
Singapore Casino
Singapore Casino Guide
yuriantibet betting agent
casino guide
yuriantibet betting agent
Singapore Casino

Posted by mian rohail at


Posted by Google at

Really i appreciate the effort you made to share the knowledge. This is really a great stuff for sharing. Keep it up . Thanks for sharing.

Posted by J2me Programming Assignment Help at

Some people do work for the Apache Software Foundation but the mostly people are volunteers like myself. A lot of the software is written by those that do not “work for” the foundation. Generally, if you commit time to a project typically knows you by awarding you committer status. Our native writers are fortified to turn your strategy write my essay please into an outstanding piece of work that will deliver an impression on its reader.

Posted by write my essay please at

Welcome to the All assignment help Reviews, Here you can get the best assignment help review sites. We strongly urge you to check our entire website once and we will assure you will find this review website very useful. Our hard work will be rewarded if students like you will appreciate our effort and spread the message about this site with your class-fellows and friends

Posted by All assignment help Reviews at

Very nice post. Interesting news.

Posted by Arkady2 at

Thanks you for sharing

Posted by website designing company in India at

norton online chat
norton symantec endpoint protection
norton 360 will not uninstall
removal norton tool
norton internet security reinstall
norton 360 install
symantec phone support
redownload norton 360
norton toolbar
norton 360 removal tool

Posted by Norton Support at

Add your comment