Skip to content

Instantly share code, notes, and snippets.

@kongkrit
Last active September 13, 2025 19:22
Show Gist options
  • Save kongkrit/70c17b85ab0c3c6b445433b2f8597bc6 to your computer and use it in GitHub Desktop.
Save kongkrit/70c17b85ab0c3c6b445433b2f8597bc6 to your computer and use it in GitHub Desktop.
svg icons in HTML that doesn't trigger CORS when served with file://

I tried to find a clean way to embed SVGs into my project without triggering CORS, especially when the project is served via file://. I am too lazy to lanch a localhost http server. here it is:

<!-- index.html  (only ONE mention of icons.svg) -->
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Three coloured arrows</title>
  <style>
    svg { width: 48px; height: 48px; }
    .red   svg { color: #e74c3c; }
    .green svg { color: #27ae60; }
    .blue  svg { color: #3498db; }
  </style>
</head>
<body>

  <button id="b1" type="button" aria-label="b1" class="red"></button>
  <button id="b2" type="button" aria-label="b2" class="green"></button>
  <button id="b3" type="button" aria-label="b3" class="blue"></button>

  <script src="copy.js"></script>
  <script>
    document.getElementById("b1").innerHTML = icons.copy;
	document.getElementById("b2").innerHTML = icons.copy;
	document.getElementById("b3").innerHTML = icons.copy;
  </script>
</body>
</html>

and copy.js

(function (root){
  root.icons = root.icons || {};
  root.icons.copy = `

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
  <style>
    svg { color:#0b0b0c; }
    @media (prefers-color-scheme: dark) { svg { color:#e8e8ea; } }
    @media (forced-colors: active) { svg { color: CanvasText; } }
  </style>
  <g fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
	<rect x="9" y="9" width="13" height="13" rx="2" ry="2"/>
	<path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/>
</svg>

`;
})(globalThis);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment