title: How to tell Service Worker which files to cache
body: <h3>What I’m doing</h3>
  
  <p>I’m building a Service Worker component. I want it to have:</p>
  
  <ul>
  <li>A single worker.js file containing the Service Worker implementation.</li>
  <li>I want to be able to tell the worker which files to cache, as well as the name of the cache.
  
  <ul>
  <li><em>Why?</em> I want to require this module in several projects and I don’t want any of them to modify the worker file. The worker should be able to receive a list of paths to cache.</li>
  </ul></li>
  </ul>
  
  <h3>What I’ve tried</h3>
  
  <ul>
  <li>I tried passing a configuration object to the register method but it didn’t work. The worker didn't receive the object.</li>
  <li>Taking advantage of the postMessage API which is available on the worker I did this:
  
  <ol>
  <li>In the registration of the worker, I’ve sent a message to the worker containing an object with the routes to cache.</li>
  <li>Inside the worker, I’ve subscribed the worker to this message and used the paths to create the cache.</li>
  </ol></li>
  </ul>
  
  <blockquote>
    <p>See it for yourself</p>
  </blockquote>
  
  <h3>Registration of the worker in the main thread</h3>
  
  <pre><code>if ('serviceWorker' in navigator) {
      navigator.serviceWorker.register('/worker.js').then(function(reg) {
          navigator.serviceWorker.controller.postMessage({
              'hello': 'world',
              cacheName: 'v1',
              urlsToCache: [
                  "/index.html"
              ]
          });
      }, function(err) {
          console.log('ಠ_ಠ   Nope.', err);
      });
  }
  </code></pre>
  
  <h3>The worker file</h3>
  
  <pre><code>'use strict';
  
  var cacheName,
      urlsToCache;
  
  importScripts('/node_modules/serviceworker-cache-polyfill/index.js');
  
  self.addEventListener('message', function (evt) {
      cacheName = evt.data.cacheName;
      urlsToCache = evt.data.urlsToCache;
  });
  
  self.addEventListener('install', function(event) {
      setTimeout(function(){
          event.waitUntil(
              caches.open(cacheName)
              .then(function(cache) {
                  console.log('Opened cache:', cache);
                  return cache.addAll(urlsToCache);
              })
          );
      }, 2000);
  
  });
  </code></pre>
  
  <h3>What is wrong with this?</h3>
  
  <p>I had to delay the opening of the cache by using a setTimeout, which is wrong, ugly and unreliable. </p>
  
  <h3>What are you trying to achieve, man? ಠ_ಠ</h3>
  
  <p>I want to find a way to tell the worker to wait until the message containing the paths to cache arrives.</p>
  
  <blockquote>
    <p>Link to my <a href="https://github.com/cristianelias/serviceworker_component" rel="nofollow">repo</a></p>
  </blockquote>
  
  <p>Thanks in advance.</p>