Published
Edited
Feb 26, 2019
Importers
6 stars
Insert cell
Insert cell
// slight modification of:
// https://github.com/uupaa/dynamic-import-polyfill/blob/master/importModule.js
// see LICENSE below
function importModule(url) {
try { // if dynamic import is supported, don't bother with the stuff below
return (new Function(`return import("${url}")`))();
} catch (err) {
}
function toAbsoluteURL(url) {
const a = document.createElement("a");
a.setAttribute("href", url); // <a href="hoge.html">
return a.cloneNode(false).href; // -> "http://example.com/hoge.html"
}

return new Promise((resolve, reject) => {
const vector = "$importModule$" + Math.random().toString(32).slice(2);
const script = document.createElement("script");
const destructor = () => {
delete window[vector];
script.onerror = null;
script.onload = null;
script.remove();
URL.revokeObjectURL(script.src);
script.src = "";
};
script.defer = "defer";
script.type = "module";
script.onerror = () => {
reject(new Error(`Failed to import: ${url}`));
destructor();
};
script.onload = () => {
resolve(window[vector]);
destructor();
};
const absURL = toAbsoluteURL(url);
const loader = `import * as m from "${absURL}"; window.${vector} = m;`; // export Module
const blob = new Blob([loader], { type: "text/javascript" });
script.src = URL.createObjectURL(blob);

document.head.appendChild(script);
});
}
Insert cell
Insert cell
Insert cell
module = importModule('https://api.observablehq.com/d/5c1af53209dddb2d.js')
Insert cell
Insert cell
importAll('5c1af53209dddb2d')
Insert cell
async function importAll(id){
const url = id.match(/\//) ? id : 'd/' + id;
const module = await importModule(`https://api.observablehq.com/${url}.js`);
console.log(module);
return `import {${
// TODO: don't import both "viewof XX" and "XX"
// Note that this skips imported cells
module.default.modules[0].variables.filter(v => !v.from).filter(v => v.name).map(d => d.name).join(', ')
}} from "${id}"`;
}
Insert cell
Insert cell
// https://gist.github.com/ebidel/3201b36f59f26525eb606663f7b487d0
function supportsDynamicImport() {
try {
new Function('import("")');
return true;
} catch (err) {
return false;
}
}
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more