我想问一下服务人员。我制作了一个Web应用程序,并尝试实现服务工作者。我将.hbs用于视图布局,并且在缓存静态文件时,无法缓存.hbs.css.js文件。


public/


css/


style.css

js/


app.js

manifest.json
service-worker.js

views/


home.hbs
partial/


header.hbs
* footer.hbs




部署应用程序时,它无法缓存home.hbsstyle.cssapp.js文件;我无法离线访问我的网站。

我该怎么解决?

这是我的app.js

if ('serviceWorker' in navigator) {

  navigator.serviceWorker
    .register('./service-worker.js', { scope: './service-worker.js' })
    .then(function(registration) {
      console.log("Service Worker Registered");
    })
    .catch(function(err) {
      console.log("Service Worker Failed to Register", err);
    })

}

var get = function(url) {   return new Promise(function(resolve, reject) {

    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState === XMLHttpRequest.DONE) {
            if (xhr.status === 200) {
                var result = xhr.responseText
                result = JSON.parse(result);
                resolve(result);
            } else {
                reject(xhr);
            }
        }
    };

    xhr.open("GET", url, true);
    xhr.send();

  });  };


这是我的服务人员:

var cacheName = 'v1'; var cacheFiles = [    './login',   './css/styles.css',    './js/app.js',   ]; self.addEventListener('install', function(e) {
    console.log('[ServiceWorker] Installed');

    // e.waitUntil Delays the event until the Promise is resolved
    e.waitUntil(

        // Open the cache
        caches.open(cacheName).then(function(cache) {

            // Add all the default files to the cache           console.log('[ServiceWorker] Caching cacheFiles');          return cache.addAll(cacheFiles);
        })  ); // end e.waitUntil });


self.addEventListener('activate', function(e) {
    console.log('[ServiceWorker] Activated');

    e.waitUntil(

        // Get all the cache keys (cacheName)       caches.keys().then(function(cacheNames) {           return Promise.all(cacheNames.map(function(thisCacheName) {

                // If a cached item is saved under a previous cacheName
                if (thisCacheName !== cacheName) {

                    // Delete that cached file
                    console.log('[ServiceWorker] Removing Cached Files from Cache - ', thisCacheName);
                    return caches.delete(thisCacheName);
                }           }));        })  ); // end e.waitUntil

});


self.addEventListener('fetch', function(e) {    console.log('[ServiceWorker] Fetch', e.request.url);

    // e.respondWidth Responds to the fetch event   e.respondWith(

        // Check in cache for the request being made        caches.match(e.request)


            .then(function(response) {

                // If the request is in the cache
                if ( response ) {
                    console.log("[ServiceWorker] Found in Cache", e.request.url, response);
                    // Return the cached version
                    return response;
                }

                // If the request is NOT in the cache, fetch and cache

                var requestClone = e.request.clone();
                fetch(requestClone)
                    .then(function(response) {

                        if ( !response ) {
                            console.log("[ServiceWorker] No response from fetch ")
                            return response;
                        }

                        var responseClone = response.clone();

                        //  Open the cache
                        caches.open(cacheName).then(function(cache) {

                            // Put the fetched response in the cache
                            cache.put(e.request, responseClone);
                            console.log('[ServiceWorker] New Data Cached', e.request.url);

                            // Return the response
                            return response;

                        }); // end caches.open

                    })
                    .catch(function(err) {
                        console.log('[ServiceWorker] Error Fetching & Caching New Data', err);
                    });


            }) // end caches.match(e.request)   ); // end e.respondWith });


我应该怎么做才能缓存.hbs文件?

最佳答案

我认为您应该像在应用路由器上调用.hbs一样调用它们。

如果您的路由器中有:

router.get('/home', (req, res) => {
    res.render('home');
});


然后可以在服务工作者中将其缓存为:

var filesToCache = [
'/home',
'css/style.css',
'js/app.js'
];


js前面没有点,并且您拼写了“样式”。
希望可以帮助某人

关于javascript - node.js-使用Service Worker缓存handlebars.js,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45774057/

10-11 09:08