We want to do offline first, the first thing we need to do is we should able to catch the browser request and return our cache data from serice worker. So user won't go to the real server to fetch data. So let's see how to do that:
self.addEventListener('fetch', function(event) {
event.respondWith(
new Response('Hello world');
)
});
We use 'respondWith() and Response()' to provdie a custom cache response.
After you reopen the browser, you will see 'Hello World'.
What if we want to show html instead of pain text? The 'Response()' take a second param which can set header.
self.addEventListener('fetch', function(event) {
event.respondWith(
new Response('Hello <b class="a-winner-is-me">world</b>', {
headers: {'Content-Type': 'text/html'}
});
)
});