[英]node.js - Caching handlebars.js using service worker
I want to ask about service workers.我想问一下服务人员。 I made a web application and try to implement services worker.
我制作了一个 Web 应用程序并尝试实现服务工作者。 I'm using
.hbs
for my views layout and when I cache static files I can't cache the .hbs
, .css
and .js
files.我将
.hbs
用于我的视图布局,当我缓存静态文件时,我无法缓存.hbs
、 .css
和.js
文件。
public/
css/
style.css
js/
app.js
manifest.json
service-worker.js
views/
home.hbs
partial/
header.hbs
* footer.hbs
header.hbs
* footer.hbs
When I deploy my app it fails to cache the home.hbs
, style.css
and my app.js
file;当我部署我的应用程序时,它无法缓存
home.hbs
、 style.css
和我的app.js
文件; I cant access my web offline.我无法离线访问我的网站。
What should I do to fix it?我应该怎么做才能修复它?
This is my 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();
}); };
This is my service worker:这是我的服务人员:
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 });
What should I do so I can cache the .hbs
file?我应该怎么做才能缓存
.hbs
文件?
I think you should call the .hbs the same way you would call them on your app router.我认为您应该像在应用路由器上调用它们一样调用 .hbs。
If you have in your router :如果您的路由器中有:
router.get('/home', (req, res) => {
res.render('home');
});
then in your service worker you can cache it like:然后在您的服务工作者中,您可以像这样缓存它:
var filesToCache = [
'/home',
'css/style.css',
'js/app.js'
];
No dot before js, and you mispelled 'style'. js 之前没有点,你拼错了“风格”。 Hope that helps someone
希望能帮助某人
Your service worker code is really bad.你的服务工作者代码真的很糟糕。 I hope there is a typo, but the
cache.addAll()
funciton is commented out!我希望有一个错字,但是
cache.addAll()
函数被注释掉了!
Anyway, I will give this a try...无论如何,我会试试这个......
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();
})
);
});
...
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.