A Runtime ImportMap Example - now as a module
While it's not possible to define a <script type="importmap">
within a module, it is possible to define it in a synchronous <script>
tag, as long as it's before any module starts executing.
Example (works in Chrome / Edge / WebKit / Safari / Firefox)
<!DOCTYPE html>
<html lang="en">
<head>
<!-- a synchronous script -->
<script>
(() => {
// any needed import path
const imports = {
'vanilla-elements': 'https://cdn.skypack.dev/vanilla-elements/'
};
// any useful feature detection (builtin extends in this case)
try {
class Script extends HTMLScriptElement {}
customElements.define('no-💩', Script, {extends: 'script'});
new Script;
}
catch (o_O) {
imports['vanilla-elements'] = 'https://cdn.skypack.dev/vanilla-elements/poly';
}
// the importmap script
const script = document.createElement('script');
script.type = 'importmap';
script.textContent = JSON.stringify({imports});
document.head.appendChild(script);
})();
</script>
<!-- any module -->
<script type="module">
import {define, HTML} from 'vanilla-elements';
define('hello-world', class extends HTML.Body {
connectedCallback() {
this.innerHTML = '<h1>Hello World 👋</h1>';
}
});
</script>
</head>
<body is="hello-world"></body>
</html>
This is now a module