Skip to content

Instantly share code, notes, and snippets.

@julkue
Last active January 11, 2022 18:39
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 julkue/fef5cf5bd11b5f2323386a51d8c51eab to your computer and use it in GitHub Desktop.
Save julkue/fef5cf5bd11b5f2323386a51d8c51eab to your computer and use it in GitHub Desktop.
Example of HTML import with Shadow DOM (isolated CSS)
1. Install e.g. http-server globally (https://www.npmjs.com/package/http-server)
2. Run http-server in this folder
3. Open http://localhost:8080/ in Chrome (there are polyfills available to make it work in other browsers too)
<template id="external">
<div>
<style>
h3 {
color: red;
}
</style>
<h3>Styled Heading</h3>
</div>
</template>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>MyZurich Test</title>
<link rel="import" href="external.html">
</head>
<body>
<h3>Unstyled Heading</h3>
<div id="target"></div>
<script>
// Load the external file
var link = document.querySelector('link[rel="import"]');
var content = link.import;
var template = content.querySelector('template');
var templateContent = document.importNode(template.content, true);
// Inject the content into a Shadow DOM element
document.getElementById('target').attachShadow({mode: 'open'}).appendChild(templateContent);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment