Created
January 24, 2020 15:23
-
-
Save konstantinmuenster/471387b307482ab7c8dd1fed392b036d to your computer and use it in GitHub Desktop.
Service Worker Rendering - Fetch Event
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
self.addEventListener('fetch', function(event) { | |
var requestURL = new URL(event.request.url); | |
if (/^\/post\//.test(requestURL.pathname)) { | |
event.respondWith( | |
Promise.all([ | |
caches.match('/post/', {ignoreSearch: true}).then(function(response) { | |
return response.text(); | |
}), | |
caches.match('https://jsonplaceholder.typicode.com/posts').then(function(response) { | |
return response.json(); | |
}) | |
]).then(function(responses) { | |
var html = responses[0]; | |
var data = responses[1]; | |
var postData = data.find(x => x.id == requestURL.searchParams.get("id")); | |
var template = Handlebars.templates.post; | |
var postHtml = template(postData); | |
var finalHtml = html.replace('<div id="output"></div>', postHtml); | |
return new Response(finalHtml, {headers: {'content-type': 'text/html'}}); | |
}) | |
) | |
} else { | |
// Other caching strategies | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment