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
<svg width="35" height="35" viewBox="0 0 35 35" xmlns="http://www.w3.org/2000/svg"><title>×</title><path d="M.608 29.304l5.472 5.472 11.592-11.592 11.52 11.592 5.472-5.472-11.592-11.52 11.592-11.52L29.192.792l-11.52 11.52L6.224.792.752 6.264 12.2 17.784.608 29.304z" fill="#000" fill-rule="evenodd"/></svg>
<!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