Created
November 13, 2015 11:51
-
-
Save roman01la/88c3374f7e0c1478066e to your computer and use it in GitHub Desktop.
Inline SVG <img> using ServiceWorker
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
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<title>Inline SVG <img> 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> |
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', (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