node.js - 如何使用服务 worker 缓存handlebars.js

标签 node.js handlebars.js google-cloud-platform service-worker

我想询问有关服务人员的问题。我制作了一个网络应用程序并尝试实现服务 worker 。我使用 .hbs 作为 View 布局,当我缓存静态文件时,我无法缓存 .hbs、.css 和 .js 文件。

这就是我保存文件的方式:

public/
 css/
   style.css
  js/
   app.js
  manifest.json
  service-worker.js
views/
  home.hbs
  partial/
   header.hbs 

当我部署应用程序时,它无法缓存 home.hbs、style.css 和我的 app.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();

  });  };

这是我的 service-worker.js

var cacheName = 'v1';
var cacheFiles = [
    './',
    './home',
    './login',
'./welcome',
'./register',
'./css/styles.css',
'./js/app.js',
'./images/fb-logo.png',
'./images/g-logo.png',
'./images/t-logo.png',
'./images/logofix.png',
'./images/icon192.png',
'https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js',
'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css',
'https://fonts.googleapis.com/css?family=Ubuntu:300,400,500,700',
'https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.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 文件? 谢谢

最佳答案

尝试这种方式,不带点,并向安装程序添加一个skipWaiting函数。 (顺便说一句,您正在缓存“styles.css”,而在树中我读到“style.css”)

var cacheName ='v2';
var filesToCache = [
'/',
'public/css/style.css',
'js/app.js',
'views/home.hbs',
];


self.addEventListener('install', function(e) {
  console.log('[ServiceWorker] Install');
  e.waitUntil(
    caches.open(cacheName).then(function(cache) {
      console.log('[ServiceWorker] Caching app shell');
      return cache.addAll(filesToCache);
    }).then(function() {
        return self.skipWaiting();
    })
  );
});
...
...

关于node.js - 如何使用服务 worker 缓存handlebars.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45778465/

相关文章:

python - 部署具有所有包依赖项的 Python Cloud Function

google-cloud-platform - 动态创建异常聚合器

jquery - 如何解决 Bootstrap node.js 应用程序中未定义的错误 "Cannot set property ' emulateTransitionEnd'?

mysql - Sequelize 中的 findAll() 找不到在事务中创建的行

Linux:让服务永远运行直到我停止它? Node.js + Socket.io

netbeans - 如何在 Netbeans 8 中为 *.handlebars 文件启用语法突出显示

docker - 如果 Google PUBSUB 中没有来自发布者的消息,如何让订阅者休眠

Node.js & Crypto : Store the current state of a crypto. createHash 实例稍后重用

jquery - 在 handlebars js 中使用 CSS(或 Jquery)为新的 "content"设置动画

node.js - Handlebars - 将内容从部分添加到 View 头部