Skip to content

Instantly share code, notes, and snippets.

@samthor
Last active September 7, 2017 03:16
Show Gist options
  • Save samthor/8c5ebf3239bfeaca6c92299bb12b2a79 to your computer and use it in GitHub Desktop.
Save samthor/8c5ebf3239bfeaca6c92299bb12b2a79 to your computer and use it in GitHub Desktop.
ES6 module hacks and nuances

TODO

Hashed modules are different

import './banana.js';
import './banana.js#foo';

These are both run by Chrome 61, but are only fetched from the network once!

With a caveat: throwing new Error() and catching it in the window.onerror handler seems to always contain the same (the top-most?) filename, on the Event.filename property. 🤦

Emulating document.currentScript

<script type="module">
  document.emulatedCurrentScript = document.getElementById('some-id');
</script>
<script type="module" id="some-id">
  // TODO: use here or in submodules
</script>

Or at runtime:

const scriptFactory = (code, id) => {
  const s = document.createElement('script');
  s.async = false;  // important, to run in order
  s.type = 'module';
  s.textContent = code;
  if (id) { s.id = id; }
  document.body.appendChild(s);
  return s;
};

const id = 'whatever';
scriptFactory(`document.emulatedCurrentScript = ${id}`);
scriptFactory(`// TODO: use here or in submodules`);

You could replace the awkward ID-ness with a second module that both scripts initially import, that handles the creation/teardown.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment