Skip to content

Instantly share code, notes, and snippets.

@WebReflection
Last active May 1, 2024 19:31
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save WebReflection/5fc85856bba3d6eef794877fb5fa2a52 to your computer and use it in GitHub Desktop.
Save WebReflection/5fc85856bba3d6eef794877fb5fa2a52 to your computer and use it in GitHub Desktop.

A Runtime ImportMap Example

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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment