Last active
January 11, 2022 18:39
-
-
Save julkue/fef5cf5bd11b5f2323386a51d8c51eab to your computer and use it in GitHub Desktop.
Example of HTML import with Shadow DOM (isolated CSS)
This file contains hidden or 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
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) |
This file contains hidden or 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
<template id="external"> | |
<div> | |
<style> | |
h3 { | |
color: red; | |
} | |
</style> | |
<h3>Styled Heading</h3> | |
</div> | |
</template> |
This file contains hidden or 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> | |
<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