node.js - 如何使用服务工作者缓存handlebars.js [英] node.js - how Caching handlebars.js using service worker
问题描述
这就是我保存我的文件:
public /
css /
style.css
js /
app.js
manifest.json
service-worker.js
views /
home.hbs
partial /
header.hbs
当我部署我的应用程序时,它无法缓存home.hbs,style.css和我的app.js文件;我无法离线访问我的网站。
我应该怎么做才能解决它?
这是我的应用程序。 js:
pre $ if('naviter'in navigator){
navigator.serviceWorker
.register('./ service-worker.js',{scope:'./service-worker.js'})
.then(function(registration){
console.log(Service Worker注册);
})
.catch(函数(err){
console.log(服务工作者无法注册,错误);
})
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');
$ b $ // e.waitUntil延迟事件直到Promise已解决
e.waitUntil(
//打开缓存
caches.open(cacheName).then(function(cache){
//将所有默认文件添加到缓存
console.log('[ServiceWorker]缓存cacheFiles');
return cache.addAll(cacheFiles);
})
); // end e.waitUntil
});
self.addEventListener('activate',function(e){
console.log('[ServiceWorker] Activated');
e .waitUntil(
//获取所有缓存键(cacheName)
caches.keys()。then(function(cacheNames){
return Promise.all(cacheNames.map (function(thisCacheName){
//如果一个缓存项保存在前一个缓存名下
if(thisCacheName!== cacheName){
// // Delete缓存文件
console.log('[ServiceWorker]从缓存中移除缓存文件 - ',thisCacheName);
return caches.delete(thisCacheName);
}
})) ;
})
); // end e.waitUntil
});
self.addEventListener('fetch',function(e){
console.log('[ServiceWorker] Fetch',e.request.url);
// e.respondWidth响应获取事件
e.respondWith(
//在缓存中检入正在发出的请求
caches.match(e (请求)
.then(函数(响应){
//如果请求在缓存中
if(response){
console.log([ServiceWorker] Found in Cache,e.request.url,response);
//返回缓存版本
返回响应;
}
//如果请求不在缓存中,则获取并缓存
$ b $ var requestClone = e.request.clone();
fetch(requestClone)
.then(函数(响应){
if(!response){
console.log([ServiceWorker]没有响应)
返回响应;
}
var responseClone = response.clone();
//打开缓存
caches.open(cacheName).then(函数(缓存){
//将提取的响应放入缓存
cache.put(e.request,responseClone);
console.log('[ServiceWorker] New Data Cached',e.request.url);
//返回响应
返回响应;
}); //结束caches.open
$ b $)
.catch(函数(err){
console.log('[ServiceWorker]错误获取和缓存新数据',err );
});
})//结束caches.match(e.request)
); // end e.respondWith
});
我该怎么做才能缓存.hbs文件?
谢谢
试试这种方式,没有点,并且向安装程序添加skipWaiting函数。 (顺便说一句,你正在缓存styles.css,而在树中,我读了style.css)
$ p $ 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); $ b $ (){
return self.skipWaiting();
})
);
});
...
...
I want to ask about service workers. I made a web application and try to implement services worker. I'm using .hbs for my views layout and when I cache static files I can't cache the .hbs, .css and .js files.
this is how i save my file:
public/
css/
style.css
js/
app.js
manifest.json
service-worker.js
views/
home.hbs
partial/
header.hbs
When I deploy my app it fails to cache the home.hbs, style.css and my app.js file; I cant access my web offline.
What should I do to fix it?
This is my 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.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
});
What should I do so I can cache the .hbs file? thank you
Try this way, without the dots, and add a skipWaiting function to the installer. (BTW you are caching "styles.css" while in the tree I read "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 - 如何使用服务工作者缓存handlebars.js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!