Is there any way to cache all files of defined folder/path in service worker?

service worker cache example
service worker caching strategies
service worker update cache
service worker cache external resources
service worker cache json
service worker cache vs browser cache
service worker precache

In service worker, I can define array of resource those are being cached during service worker get started mentioned below:

self.addEventListener('install', event => {
        .then(cache => cache.addAll([

How can I define a path/directory in service worker, so that instead of writing all files name, service worker pick all files from given path/directory and add all in cache?

That is not possible. The SW (or the browser, for that matter) doesn't have any clue about the files in a specific path on the web server. You have to give the names of the files you want to be cached. More on the same issue here.

Are you using some build tooling to automatically generate the list of files? If not, you most likely should :)


One of the most used libraries for SW tooling is Workbox. They offer both runtime-caching and precaching of assets. They also have build tooling plugins for eg. Webpack and Gulp.

Runtime-caching works by giving the asset from the cache if it exists in there and anyway updating it from the server. Basically every new asset will be initially requested from the network and then returned from the cache on subsequent requests.


Yes, you can use Workbox without NPM to some extent. You need to run NPM scripts etc. to gather the filenames for files to be cached BUT you can still implement runtime-caching just by importing the Workbox.js script in your hand-written SW file.

Just by saying


At the top of your SW imports the latest (as of now) version of Workbox. You can see that's what happens in the runtime-caching example here too.

You can also download the .js file above and place it on your own server and import it from a relative path instead.

Lab: Caching Files with Service Worker | Web, Through service workers, all framework and application code to output the HTML view Indeed, I'd argue that there is no other way but to hook into these functions, Caching External Resources: Define a List of Domains, and Validate the We can place the service-workers.js file in any directory, such as� If the promise rejects, the installation is considered a failure and this service worker is abandoned (if an older version is running, it stays active). cache.addAll will reject if any of the resources fail to cache. This means the service worker will only install if all of the resources in cache.addAll have been cached. On user interaction

Runtime caching using Workbox sw.



const assetRoute = new workbox.routing.RegExpRoute({
    regExp: new RegExp('^http://localhost:8081/jobs/static/*'),
    handler: new workbox.runtimeCaching.CacheFirst()

const router = new workbox.routing.Router();
router.registerRoutes({routes: [assetRoute]});
    handler: new workbox.runtimeCaching.CacheFirst()

Script in my html file to load Servcie worker.

    if ('serviceWorker' in navigator) {
        window.addEventListener('load', function() {
            navigator.serviceWorker.register('http://localhost:8081/jobs/static/service-worker.js?v=4').then(function(registration) {
            // Registration was successful
            console.log('ServiceWorker registration successful with scope: ', registration.scope);
        }, function(err) {
            // registration failed :(
            console.log('ServiceWorker registration failed: ', err);

Caching Files with Service Worker | Web, This module takes a list of files to cache and generates a service worker at build Service worker works well with an app shell strategy, where the app's main All of the Polymer build presets, and the default build, include a service worker. a configuration file called sw-precache-config.js in your top-level project folder. The Cache interface provides a storage mechanism for Request / Response object pairs that are cached, for example as part of the ServiceWorker life cycle. Note that the Cache interface is exposed to windowed scopes as well as workers. You don't have to use it in conjunction with service workers, even though it is defined in the service worker spec.

Yes you can. I have also such kind of problem and I find cool solution using performance. Here is my sw.js:

const KEY = 'key';

self.addEventListener('install', (event) => {

self.addEventListener('message', (event) => {
    if ( === 'CACHE_URLS') {
                .then( (cache) => {
                    return cache.addAll(;

Here is my main.js:

if ('serviceWorker' in navigator) {
    navigator.serviceWorker.register('/sw.js', { scope: '/' })
        .then((registration) => {
            const data = {
                type: 'CACHE_URLS',
                payload: [
                    ...performance.getEntriesByType('resource').map((r) =>
        .catch((err) => console.log('SW registration FAIL:', err));

By this you can also add some filter which will cache specific path.

How Service Worker Cache Works, Using a Service worker you can easily set an app up to use cached assets This is central to the way service workers work. It also registers, installs, and activates a service worker, and when more of the spec is supported by browsers it will cache all the files But the path needs to be written as /sw-test/sw.js , not / sw.js . The default scope is the location of the service worker file, and extends to all directories below. So if service-worker.js is located in the root directory, the service worker will control requests from all files at this domain. You can also set an arbitrary scope by passing in an additional parameter when registering. For example: main.js

Yes. To cache many files from multiple directories ... I use a helper function in the service worker that I named "getFileArray( ... )." It takes one string argument of the directory name. For multiple directories, I use an array of these in Promise.all:

let cache_name = "cache-A";
let filesToCache = [

self.addEventListener( `install`, eo => {
    eo.waitUntil( filesAreCached() );
} );

///////| helper functions |/////////
function filesAreCached(){

        /* name the directories whose files you wish to cache */
        getFileArray( "js" ),
        getFileArray( "css" ),
        getFileArray( "images" ),
        getFileArray( "screens" ),
        getFileArray( "modals" )        
    .then( promiseArray => {
        let promisedFiles = [];
        promiseArray.forEach( array => {
            promisedFiles = promisedFiles.concat( array ) ;
        } );
        return promisedFiles;       
    .then( promisedFiles => {
        filesToCache = filesToCache.concat( promisedFiles );
        console.log( `Cached files:`, filesToCache  );
        return cache_name );
    .then( cache => cache.addAll( filesToCache ) );

 the following function calls a server script that returns an array of filenames,
 each one prepended with the directory name:  
async  function getFileArray( directory ){
    let form = new FormData();
    form.append( `directory`, directory );
    let fileArray = await fetch( `php/getFileArray.php`, { method: `POST`, body: form })
    .then( response => response.json() ) ;

    return fileArray;

The PHP code looks like this:

Motivation: To help provide an accurate list of files
for JavScript service workers to cache. Saves time,
tedium, and possible typos in doing it manually.

Use the POSTed directory path to return an array
that lists all the files in that directory,
less the "." and ".." entries.
Prepend the directory name to the filename so that
we have the "full path" to the file.
Return this array as a json string.
     $directory = $_POST["directory"] ;
     $filelistArray = scandir( "../" . $directory );
     $cleanFileArray =  array();
     foreach( $filelistArray  as $file ){
         if ( $file !== "." and $file !== ".." ){
                array_push( $cleanFileArray, $directory . "/" . $file );
     $fileArrayJson = json_encode( $cleanFileArray );
     exit( $fileArrayJson );

Of course, any backend language can be used. This technique might be a little unsophisticated, but it works for me :)

Implementing A Service Worker For Single-Page App WordPress Sites, Caching provides a mechanism for storing request/response object pairs in the browser. This Duration: 9:44 Posted: 26 Apr 2017 Caveat: By default, the log file path (in line 11) should be able to use a relative path with respect to the assembly entry file. However, when an application is hosted in a Windows Service, the current working directory is set to the “ C:\WINDOWS\system32 ” folder, which is not a good place for log files.

Offline caching with Service Worker Precache, Learn all about the multiple PWA caching configuration options of the Along the way, we will learn about the Angular Service Worker This flag will cause the production build to include a couple of extra files in the output dist folder: applied and replaced with the paths of any files that matched them. Common files used by all instances on a single computer are installed in the folder <drive>:\Program Files\Microsoft SQL Server nn\. <drive> is the drive letter where components are installed. The default is usually drive C. nnn identifies the version. The following table identifies versions for the paths. {nn} is the version value used in the

Using Service Workers, make your Next.js application work offline using service workers via Google's workbox Cache Strategies; Service worker path; next export; Development mode; Next The easiest way to do that is creating a server.js that looks like this: will precache all the Next.js webpack emitted files and the user-defined static ones� Hi net_tech, If you want to clear MS Teams cache,you could refer to the following ways. 1. Fully exit the Microsoft Teams desktop client. To do this, either right click Teams from the Icon Tray and select ‘Quit’, or run Task Manager and fully kill the process.

Caching Files with the Service Worker, Files found in every folder in the path from the drive root to the current folder (where nuget.exe is invoked or the folder containing the Visual Studio project). For example, if a command is invoked in c:\A\B\C, NuGet looks for and loads config files in c:, then c:\A, then c:\A\B, and finally c:\A\B\C.

  • Thank you @pate. Now am thinking to automatically generate the list of files. Can you suggest me the best way to do this.
  • Can I cache at run time?
  • I read workbox theory. It is also required Node and npm. It can be used without Node and npm? Any example will be very helpful.
  • @MhodYasin Yes, it can be used. Check out my updated answer.
  • Hi @pate, below i posted sample code to implement Workbox sw runtime caching. This is running without any error. Is it written perfectly or need any improvement? I need your feedback or help to improve this.
  • Cache all the request starting with localhost:8081/jobs/static/*