I want to use ServiceWorker of javascript to cache an HTML file for offline view. But problem is I have a django application. and I don't know how can I specify my template files in service-worker.js.
I specified a URL for service-worker.js in my urls.py like this -
path('service-worker.js', (TemplateView.as_view(template_name="menu/service-worker.js", content_type='application/javascript', )), name='service-worker.js')
this is my index.html template file -
<script>
if('serviceWorker' in navigator) {
let registration;
const registerServiceWorker = async () => {
registration = await navigator.serviceWorker.register("{% url 'service-worker.js' %}");
};
registerServiceWorker();
}
</script>
everything working great so far.
this is my service-worker.js
const cacheName = 'my-cache';
const filesToCache = [
"/index.html",
];
self.addEventListener('activate', e => self.clients.claim());
self.addEventListener('install', e => {
e.waitUntil(
caches.open(cacheName)
.then(cache => cache.addAll(filesToCache))
);
});
self.addEventListener('fetch', e => {
e.respondWith(
caches.match(e.request)
.then(response => response ? response : fetch(e.request))
)
});
I'm getting this error Uncaught (in promise) TypeError: Failed to execute 'addAll' on 'Cache': Request failed and I know this is because index.html file is not found and returning 404 error. but I don't have any idea how should I specify the template file here. can anyone please help me with how should I import template files in service-worker. or I may have some totally different problem. Thank you!