Skip to content

Instantly share code, notes, and snippets.

@nfreear
Created October 2, 2022 10:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nfreear/1988f68cff4ae901b0ef52b607b90bfa to your computer and use it in GitHub Desktop.
Save nfreear/1988f68cff4ae901b0ef52b607b90bfa to your computer and use it in GitHub Desktop.
Loading non-module Javascripts using `import()`.
<!doctype html> <title> Import tests </title>
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.1/dist/leaflet.css"
integrity="sha256-sA+zWATbFveLLNqWO2gtiw3HL/lh1giY/Inf1BJ0z14="
crossorigin=""/>
<style>
#map { x-height: 180px; height: 72vh; }
button { font-size: inherit; padding: .5rem 1rem; }
</style>
<h1> Import tests </h1>
<p>Loading non-module Javascripts using <tt>import()</tt>.</p>
<article id="map" aria-label="My map"></article>
<script type="module">
(async () => {
// Import non-module JS for side-effects ('M' is empty).
const M = await import('https://unpkg.com/leaflet@1.9.1/dist/leaflet.js');
const E = await import('./import-test.mjs');
const { L } = window;
console.debug('Import:', E, M, L);
const map = L.map('map').setView([51.505, -0.09], 13);
L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);
L.marker([51.5, -0.09]).addTo(map)
.bindPopup('A pretty CSS3 popup.<br> Easily customizable.')
.openPopup();
})();
</script>
<p><button id="start-button">Start</button></p>
<script data-X-type="module">
const BTN = document.querySelector('#start-button');
BTN.addEventListener('click', async (ev) => {
// Import non-module JS for side-effects ('M' is empty).
const M = await import('https://unpkg.com/tone@14.6.14/build/Tone.js');
const { Tone } = window;
console.debug('Tone:', M, Tone);
const synth = new Tone.Synth().toDestination();
// play a middle 'C' for the duration of an 8th note
synth.triggerAttackRelease("C4", "8n");
});
</script>
<pre>
NDF, 02-Oct-2022.
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import
* https://leafletjs.com/
* https://tonejs.github.io/
</pre>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment