Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Native `import()` polyfill (Note: can't name it `import` due to reserved word limitations)
Object.defineProperty(window, Symbol.for('registry'), {
value: new Map(),
});
window.importScript = src => {
const registry = window[Symbol.for('registry')];
if (registry.has(src)) {
return registry.get(src).promise;
}
const record = {
src,
script: Object.assign(document.createElement('script'), {
type: 'module',
innerText: `
import * as X from '${src}';
window[Symbol.for('registry')].get('${src}').resolvers[0](X);
`,
onload: () => record.script.parentNode.removeChild(record.script),
onerror: err => {
registry.get(src).resolvers[1](err);
record.script.parentNode.removeChild(record.script);
},
}),
};
record.promise = new Promise((...resolvers) => record.resolvers = resolvers);
document.head.appendChild(record.script);
registry.set(src, record);
return record.promise;
};
// importScript('https://diffhtml.org/es').then(diff => console.log(diff));
@tbranyen

This comment has been minimized.

Show comment
Hide comment
@tbranyen

tbranyen May 7, 2017

Mock dependencies with:

function mock(src, value) {
  const registry = window[Symbol.for('registry')];

  if (registry.has(src)) {
    throw new Error(`Dependency ${src} already defined`);
  }

  const record = {
    src,
    promise: Promise.resolve(value),
  };

  registry.set(src, record);
  return record.promise;
}
Owner

tbranyen commented May 7, 2017

Mock dependencies with:

function mock(src, value) {
  const registry = window[Symbol.for('registry')];

  if (registry.has(src)) {
    throw new Error(`Dependency ${src} already defined`);
  }

  const record = {
    src,
    promise: Promise.resolve(value),
  };

  registry.set(src, record);
  return record.promise;
}
@tbranyen

This comment has been minimized.

Show comment
Hide comment
@tbranyen

tbranyen May 7, 2017

To handle multiple imports (like AMD) you could write a function like importScripts:

window.importScripts = srcs => Promise.all(srcs.map(src => importScript(src)));

importScripts([
  'https://diffhtml.org/es',
  'https://diffhtml.org/master/diffhtml-components',
]).then(([{ innerHTML }, { Component }]) => {
  console.log(innerHTML, Component);
});
Owner

tbranyen commented May 7, 2017

To handle multiple imports (like AMD) you could write a function like importScripts:

window.importScripts = srcs => Promise.all(srcs.map(src => importScript(src)));

importScripts([
  'https://diffhtml.org/es',
  'https://diffhtml.org/master/diffhtml-components',
]).then(([{ innerHTML }, { Component }]) => {
  console.log(innerHTML, Component);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment