Skip to content

Instantly share code, notes, and snippets.

@developit
Last active April 26, 2020 15:46
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save developit/0c2ef067c6f52c5f23f023e39a826c11 to your computer and use it in GitHub Desktop.
Save developit/0c2ef067c6f52c5f23f023e39a826c11 to your computer and use it in GitHub Desktop.

comlinkage

Dynamic import, but where the module you import runs in a different thread.

Powered by Comlink and Module Workers.

Available via unpkg: https://unpkg.com/comlinkage

Usage

Here's roughly the source for a demo where we're running Acorn in a Worker. You can view the full demo on Glitch.

import importFromWorker from 'https://unpkg.com/comlinkage';

const { parse } = importFromWorker('https://unpkg.com/acorn@7.1.0/dist/acorn.mjs');

class ShowAst extends HTMLElement {
  attachedCallback() {
    const parsed = await parse(this.textContent, { sourceType: 'module' });
    this.textContent = JSON.stringify(parsed, 0, 2);
  }
}

customElements.define('show-ast', ShowAst);
import { wrap, expose } from 'https://unpkg.com/comlink@4.2.0/dist/esm/comlink.mjs';
export default name => wrap(new Worker(import.meta.url, { name, type:'module' }));
if (name && !self.document) {
const q = []; onmessage = q.push.bind(q);
import(name).then(expose).then(() => onmessage = q.map(dispatchEvent))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment