Skip to content

Instantly share code, notes, and snippets.

@roman01la
Created November 13, 2015 11:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save roman01la/88c3374f7e0c1478066e to your computer and use it in GitHub Desktop.
Save roman01la/88c3374f7e0c1478066e to your computer and use it in GitHub Desktop.
Inline SVG <img> using ServiceWorker
Display the source blob
Display the rendered blob
Raw
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Inline SVG &lt;img&gt; with ServiceWorker</title>
</head>
<body>
<img src="image.svg">
<script>
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('service_worker.js');
} else {
console.error('ServiceWorker is not supported in this browser!');
}
</script>
</body>
</html>
self.addEventListener('fetch', (event) => {
if (event.request.url.includes('index.html')) {
event.respondWith(
// fetch HTML
fetch('index.html')
.then((res) => res.text())
.then((html) => {
// fetch SVG
return fetch('image.svg')
.then((res) => res.text())
// replace <img> with SVG contents
.then((svg) => html.replace('<img src="image.svg">', svg))
// respond with a new HTML
.then((html) => new Response(html, {
headers: new Headers({
'Content-Type': 'text/html'
})
}));
}));
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment