Search code examples
javascriptweb-worker

Prevent worker from accessing server every time it is created


I have to make my page work as usual but even when there is no network connection. The only problem is that every time worker is created, it reloads it's js file so after the connection is lost, it throws errors and does nothing. I have code:

let my_worker = null

function start(from_v, to_v){
    my_worker = new Worker('wwa_worker.js');
    my_worker.postMessage({ from_val: from_v, to_val: to_v});
    my_worker.onmessage = function (e) {
        result_field.value = e.data;
    }
}

function stop(){
    my_worker.terminate();
    my_worker = null
}

The main idea is that I have to cache worker's js file so it won't get loaded again in this session.


Solution

  • As suggested in the comments, I used service worker.

    Register the worker in main js file:

    // main.js
    
    navigator.serviceWorker.register('/service-worker.js');
    

    And then every time fetch is called, try to find the resource in cache and load it from the server if it is not present (code from MDN, version w/ fallback is also here):

    // service-worker.js
    
    self.addEventListener('fetch', (event) => {
        event.respondWith(
            caches.match(event.request).then((resp) => {
                return resp || fetch(event.request).then((response) => {
                    return caches.open('v1').then((cache) => {
                        cache.put(event.request, response.clone());
                        return response;
                    });
                });
            })
        );
    });