Dynamic imports
Updated
The npm registry holds libraries for almost anything a world needs: fake names for a crowd, a force layout for a graph, smooth noise for motion, confetti, charts. A script pulls one in from a CDN with a single line, #pragma import(Name="url"), and uses it as if it were a global. Nothing is copied into the project and nothing is bundled: the browser downloads the library when the scene loads. This page explains how a library is found and bound, how to pin it, ES modules and UMD bundles, binding several names at once, and walks through libraries that work well in a world.
Before you start
Section titled “Before you start”- Modules:
#pragma exportand#pragma import(name)between scripts. A URL import shares their registry of names. - Directives: how a
#pragmais written. - Behavior scripts: the sandbox a script runs in.
How it works
Section titled “How it works”#pragma import(Name="url") loads a JavaScript module from a URL and binds it as Name. Use it for libraries: noise functions, date formatting, charting.
#pragma import(confetti="https://cdn.jsdelivr.net/npm/canvas-confetti@1.9.3/+esm")#pragma import([Chart, registerables]="https://cdn.jsdelivr.net/npm/chart.js@4.4.4/+esm")#pragma lifecycle(startup)
function startup() { Chart.register(...registerables); log(typeof confetti);}- The module loads before the script runs, so its names are ready in top-level code.
- The loader tries the URL as an ES module first. With one name, it binds the module’s export of that name, or a global the module set, or its default export. With a list of names,
[A, B]="url", it binds each named export. - A script that is not an ES module, such as a UMD bundle, is loaded as a classic script, and the name is read from the global it sets.
- A module compiled to WebAssembly that starts its runtime after loading is awaited until it is ready, up to 60 seconds.
- Each URL loads once per page and is cached: other scripts importing the same URL get the same module.
- The URL must be
http://orhttps://, and keeps its query string:"https://example.com/lib.js?v=2". - A failed load stops the script with
Failed to import URL …. - URL imports work in editor code too: the editor loads them before running it.
Module names and exports share one registry: do not #pragma export a name that a URL import already uses.
AI tool scripts can import from a URL only when they are given permission to; see AI agents.
Pinning a version
Section titled “Pinning a version”A CDN URL names a package and, after an @, a version: https://cdn.jsdelivr.net/npm/simplex-noise@4.0.3/+esm. Always give the exact version.
- An exact version never changes, so the script runs tomorrow as it runs today, and the browser can keep it in its cache.
- A URL without a version, or with a range such as
@4, follows new releases: a library update can change what your world does, or stop it from loading, without any change to your scripts. - To move to a new version, change the number in the URL and test the world again.
On jsDelivr, /+esm at the end of a package URL serves the package as an ES module, with its own imports resolved, which is what the loader tries first.
ES modules and UMD bundles
Section titled “ES modules and UMD bundles”Libraries are published in two shapes, and the loader handles both:
| Shape | How it is loaded | Where the name comes from |
|---|---|---|
ES module, such as a /+esm URL |
Imported as a module | The export with that name; failing that, a global the module set; for a single name, the default export |
UMD or classic script, such as a .min.js bundle |
Added to the page as a script | The global the script sets, such as confetti or Chart |
Prefer the ES module: it can bind several names at once, and it does not depend on the global a bundle happens to set. Use a UMD bundle when a library is not published as a module; then the name in the pragma must be the global’s name.
Several names from one module
Section titled “Several names from one module”A list of names, [A, B]="url", binds each named export of one module:
#pragma import([forceSimulation, forceManyBody]="https://cdn.jsdelivr.net/npm/d3-force@3.0.1/+esm")- Every name in the list must be a named export of the module (or a global it sets). A list never falls back to the default export.
- The module loads once, however many names you take from it, and other scripts importing the same URL share it.
- Names are case-sensitive:
[chart]does not findChart.
Examples
Section titled “Examples”1. Visitors named by Faker
Section titled “1. Visitors named by Faker”Faker makes up realistic data: names, jobs, addresses, dates. Here it names three visitors, and R names them again.
#pragma import(faker="https://cdn.jsdelivr.net/npm/@faker-js/faker@9.9.0/+esm")#pragma lifecycle(startup, update)
let seed = 42;let badges = [];
function nameVisitors() { faker.seed(seed); // the same seed always gives the same names badges.forEach((badge) => { badge.setProps({ text: `${faker.person.fullName()}\n${faker.person.jobType()}` }); });}
function startup() { badges = ['Badge 1', 'Badge 2', 'Badge 3'].map((name) => findEntity(name).getComponent(TextComponent)); nameVisitors();}
function update() { if (!Input.keyboard.isKeyReleased(Key.R)) return; seed += 1; nameVisitors();}Faker, imported from a CDN, gives three visitors a name and a job. A fixed seed makes the names the same on every run, and R moves to the next seed.
Press R for new names. Drag to orbit the camera, scroll to zoom.
How it works:
#pragma import(faker="…/@faker-js/faker@9.9.0/+esm")binds the module’sfakerexport before the script runs.faker.seed(seed)makes Faker’s output repeatable: seed 42 gives the same three names on every run, for every player. Without a seed, each run gives different names.- R moves to the next seed, so each press shows new names, and pressing it the same number of times always shows the same ones.
- Each badge is a Text entity above its visitor;
\nbreaks the name and the job onto two lines.
2. A force-directed graph with d3-force
Section titled “2. A force-directed graph with d3-force”d3-force lays out linked nodes as if they were charged balls on springs. Here it places six balls and the lines between them, and Space scatters them to watch the layout settle again.
#pragma import([forceSimulation, forceManyBody, forceLink, forceCenter]="https://cdn.jsdelivr.net/npm/d3-force@3.0.1/+esm")#pragma lifecycle(startup, update)
const SCALE = 0.02; // simulation units to metresconst LINKS = [[0, 1], [0, 2], [0, 3], [1, 4], [2, 5], [3, 5]];
let balls = [];let nodes = [];let lines = null;let simulation = null;
function startup() { balls = self.parent.children.filter((child) => isEntity(child) && child !== self); nodes = balls.map(() => ({})); simulation = forceSimulation(nodes) .force('charge', forceManyBody().strength(-60)) .force('link', forceLink(LINKS.map(([source, target]) => ({ source, target }))).distance(40)) .force('center', forceCenter()) .stop(); // no timer: update ticks it once a frame
const ends = LINKS.flatMap(() => [new THREE.Vector3(), new THREE.Vector3()]); lines = new THREE.LineSegments( new THREE.BufferGeometry().setFromPoints(ends), new THREE.LineBasicMaterial({ color: '#f8fafc' }), ); self.parent.add(lines);}
function update() { if (Input.keyboard.isKeyReleased(Key.Space)) { nodes.forEach((node) => { node.x = Random.range(-80, 80); node.y = Random.range(-80, 80); }); simulation.alpha(1); // reheat }
simulation.tick(); nodes.forEach((node, i) => balls[i].setPosition(node.x * SCALE, node.y * SCALE, 0));
const ends = lines.geometry.attributes.position; LINKS.forEach(([a, b], i) => { ends.setXYZ(i * 2, nodes[a].x * SCALE, nodes[a].y * SCALE, 0); ends.setXYZ(i * 2 + 1, nodes[b].x * SCALE, nodes[b].y * SCALE, 0); }); ends.needsUpdate = true;}d3-force, imported from a CDN, lays out six linked balls: the simulation is ticked once a frame and its positions move the balls and the lines between them.
Watch the graph settle, then press Space to scatter it. Drag to orbit the camera, scroll to zoom.
How it works:
- One pragma binds four named exports of the same module.
.stop()stops the simulation’s own timer.updatecallssimulation.tick()once a frame instead, so the layout moves with the world, pauses with it, and stops when the script stops.- The simulation works in its own units in 2D:
SCALEturns itsxandyinto metres, andsetPositionplaces each ball, relative to the Graph entity the script sits under. - The lines are one plain line object added under the graph; their ends are rewritten every frame.
simulation.alpha(1)reheats the simulation after a scatter, so the nodes move again until they settle.
3. Confetti in front of the camera
Section titled “3. Confetti in front of the camera”canvas-confetti fires a burst of confetti. Given a canvas of its own, it draws there instead of over the page, and a plane kept in front of the camera shows that canvas over the whole view.
#pragma import(confetti="https://cdn.jsdelivr.net/npm/canvas-confetti@1.9.3/+esm")#pragma lifecycle(startup, update)
const DISTANCE = 1; // metres in front of the camera
let fire = null;let texture = null;let screen = null;
// At most one burst every half second, from a random point along the bottom.const burst = throttle(() => { fire({ particleCount: 150, spread: 80, scalar: 2, origin: { x: Math.random(), y: 0.8 } });}, 500);
function startup() { const canvas = Canvas.create(1280, 720); fire = confetti.create(canvas, { resize: false }); // draw on our canvas, not the page texture = Canvas.texture(canvas); screen = new THREE.Mesh( new THREE.PlaneGeometry(1, 1), new THREE.MeshBasicMaterial({ map: texture, transparent: true, depthTest: false }), ); screen.renderOrder = 1; // drawn over the scene self.add(screen);}
function update() { if (Input.keyboard.isKeyReleased(Key.Space)) burst(); // Keep the canvas in front of the camera, filling its view. camera.getWorldPosition(screen.position); camera.getWorldQuaternion(screen.quaternion); screen.translateZ(-DISTANCE); const height = 2 * DISTANCE * Math.tan(THREE.MathUtils.degToRad(camera.fov / 2)); screen.scale.set(height * camera.aspect, height, 1); texture.needsUpdate = true; // show the canvas's latest frame}canvas-confetti, imported from a CDN, draws on a canvas the script made, shown on a plane kept in front of the camera so the burst covers the view.
Click the scene, then press Space to fire confetti from a random spot. Drag to orbit the camera, scroll to zoom.
How it works:
confetti.create(canvas, { resize: false })returns afirefunction bound to the script’s canvas;resize: falsekeeps the sizeCanvas.creategave it.throttlemakesburstrun at most once every 500 ms, so holding or hammering Space cannot flood the canvas; each burst starts at a randomxalong the bottom.- Each frame the plane takes the camera’s position and rotation and moves one metre forward. Its height is what the camera sees at that distance,
2 × distance × tan(fov / 2), and its width that times the camera’saspect, so it fills the view, even when the window is resized. - The material is
transparent, so only the confetti shows, anddepthTest: falsewith arenderOrderdraws it over everything in the scene. - canvas-confetti animates the canvas on its own;
texture.needsUpdate = truesends each new frame to the texture.
4. Edge detection with OpenCV.js
Section titled “4. Edge detection with OpenCV.js”OpenCV.js is the OpenCV computer vision library compiled to WebAssembly. Here it finds the edges in a picture with Canny edge detection, and two planes show the picture and its edges side by side. Space tries other thresholds.
#pragma import(cv="https://cdn.jsdelivr.net/npm/@techstark/opencv-js@4.11.0-release.1/dist/opencv.js")#pragma lifecycle(startup, update)
const SIZE = 512;const THRESHOLDS = [[50, 150], [100, 200], [20, 60]]; // Canny low and highlet level = 0;let photo = null;let edges = null;let texture = null;
function addPlane(map, x) { const plane = new THREE.Mesh(new THREE.PlaneGeometry(1.4, 1.4), new THREE.MeshBasicMaterial({ map })); plane.position.x = x; self.parent.add(plane);}
function detectEdges() { const [low, high] = THRESHOLDS[level]; const source = cv.imread(photo); // RGBA pixels of the canvas const gray = new cv.Mat(); const result = new cv.Mat(); cv.cvtColor(source, gray, cv.COLOR_RGBA2GRAY); cv.Canny(gray, result, low, high); cv.imshow(edges, result); // white edges on black texture.needsUpdate = true; // Mats live in OpenCV's WebAssembly memory, which is not garbage-collected source.delete(); gray.delete(); result.delete(); log(`Canny thresholds ${low} and ${high}`);}
async function startup() { const image = await new THREE.ImageLoader().loadAsync('/example-assets/Stormtrooper_D.jpg'); photo = Canvas.create(SIZE, SIZE); photo.getContext('2d', { willReadFrequently: true }).drawImage(image, 0, 0, SIZE, SIZE); // cv.imread reads it often edges = Canvas.create(SIZE, SIZE); texture = Canvas.texture(edges); addPlane(Canvas.texture(photo), -0.75); addPlane(texture, 0.75); detectEdges();}
function update() { if (!texture || !Input.keyboard.isKeyReleased(Key.Space)) return; level = (level + 1) % THRESHOLDS.length; detectEdges();}OpenCV.js, imported from a CDN, finds the edges in a picture drawn on a script canvas with Canny edge detection, and two planes show the picture and its edges side by side.
OpenCV.js is an 11 MB download (2.8 MB compressed): wait a few seconds for the edges to appear. Then click the scene and press Space to try other thresholds. Drag to orbit the camera, scroll to zoom.
How it works:
opencv.jsis a classic script, not an ES module, so the loader adds it to the page and binds thecvit publishes. Its WebAssembly is inside the file, andcvis a promise that settles once the WebAssembly has started: the loader waits for it, socv.Matis ready whenstartupruns.- It is a big download: about 11 MB, 2.8 MB compressed. The script, and the scene’s other scripts, start only once it is in and started. The 60-second limit of How it works applies to modules that report they are ready with a callback; this build hands over a promise, and the loader waits for it without a limit, however slow the connection. After the first visit the browser serves the file from its cache.
- Keep this build. The
opencv.jsfiles of some other versions, such as 4.10.0 on docs.opencv.org, hand over acvthat the loader cannot wait for, and the page stops responding while it loads. - The script has no
documentto load an image with:THREE.ImageLoaderloads the picture, anddrawImagedraws it on a canvas made withCanvas.create.willReadFrequentlytells the browser that this canvas is read back often, bycv.imread. cv.imreadreads a canvas’s pixels into acv.Mat, an image in OpenCV’s memory.cvtColorturns it gray,Cannykeeps only the edges, andcv.imshowdraws the result on the second canvas.- A
cv.Matlives in the WebAssembly module’s own memory, which JavaScript’s garbage collector never frees. Call.delete()on every Mat once you are done with it, or each new detection leaks memory until the page runs out. texture.needsUpdate = truesends the new edges to the plane after each detection.
5. Falling boxes with Box2D
Section titled “5. Falling boxes with Box2D”Box2D is a 2D physics engine, and box2d.js is Box2D compiled to JavaScript with Emscripten. Here six boxes fall on a ground and stack, seen through an Orthographic Camera. A click kicks a box up, and Space drops them all again.
#pragma import(Box2D="https://cdn.jsdelivr.net/npm/box2d.js@1.0.4/build/Box2D_v2.3.1_min.js")#pragma lifecycle(startup, update, dispose)
const SIDE = 0.6; // box side, in metres: Box2D's units are metres tooconst STEP = 1 / 60; // Box2D wants a fixed time step, in secondsconst AWAKE = '#f59e0b';const ASLEEP = '#60a5fa'; // a body at rest that Box2D stopped simulatingconst KICK = 4; // m/s upwards a click gives a box: a gentle hop
let world = null;let point = null; // two b2Vec2s, reused to hand vectors to Box2Dlet at = null;let boxes = [];let pending = 0; // seconds of simulation not run yet
function addBody(entity, type, width, height) { const def = new Box2D.b2BodyDef(); def.set_type(type); point.Set(entity.position.x, entity.position.y); def.set_position(point); def.set_angle(entity.rotation.z); const body = world.CreateBody(def);
const shape = new Box2D.b2PolygonShape(); shape.SetAsBox(width / 2, height / 2); // half sizes body.CreateFixture(shape, 1).SetFriction(0.6); // density 1 kg/m² Box2D.destroy(shape); // Box2D keeps copies: free ours Box2D.destroy(def); return body;}
function startup() { point = new Box2D.b2Vec2(0, -9.81); at = new Box2D.b2Vec2(0, 0); world = new Box2D.b2World(point); // gravity, m/s² world.SetAllowSleeping(true); // bodies at rest sleep until something hits them
const ground = findEntity('Ground'); addBody(ground, Box2D.b2_staticBody, 8, 0.4);
boxes = self.parent.children .filter((child) => isEntity(child) && child !== self && child !== ground) .map((entity) => ({ entity, start: [entity.position.x, entity.position.y], body: addBody(entity, Box2D.b2_dynamicBody, SIDE, SIDE), material: entity.getComponent(StandardMaterialComponent), awake: true, }));}
function dropAgain() { boxes.forEach(({ body, start }) => { point.Set(start[0], start[1]); body.SetTransform(point, Random.range(-0.5, 0.5)); point.Set(0, 0); body.SetLinearVelocity(point); body.SetAngularVelocity(0); body.SetAwake(true); });}
// The box under the pointer gets an upward impulse at the point clicked, so it hops and turns a little.function kick() { const hit = GraphicsRaycaster.fromScreen(Input.mouse.position()).hit(boxes.map((box) => box.entity)); const box = hit && boxes.find((b) => b.entity === hit.entity); if (!box) return; point.Set(0, box.body.GetMass() * KICK); // impulse = mass × change in speed at.Set(hit.point.x, hit.point.y); box.body.ApplyLinearImpulse(point, at, true); // true wakes a sleeping box}
function update(dt) { if (Input.keyboard.isKeyReleased(Key.Space)) dropAgain(); if (Input.mouse.isButtonReleased(MouseButton.Left)) kick();
pending += dt; while (pending >= STEP) { world.Step(STEP, 8, 3); // velocity and position iterations pending -= STEP; } boxes.forEach((box) => { const position = box.body.GetPosition(); box.entity.setPosition(position.get_x(), position.get_y(), 0); box.entity.setRotation(0, 0, box.body.GetAngle());
const awake = box.body.IsAwake(); if (awake !== box.awake) { box.awake = awake; // recolour only when the state changes box.material.setProps({ color: awake ? AWAKE : ASLEEP }); } });}
function dispose() { Box2D.destroy(world); // frees every body with it Box2D.destroy(point); Box2D.destroy(at);}Box2D, the 2D physics engine compiled to JavaScript, imported from a CDN, drops six boxes on a ground seen through an Orthographic Camera, and a click kicks a box up: the script steps the Box2D world every frame and copies each body's position and angle to its box.
Watch the boxes fall and stack. Click a box to kick it up, or click the scene and press Space to drop them all again.
How it works:
Box2D_v2.3.1_min.jsis a classic script that sets a globalBox2D, not an ES module: the loader adds it to the page and binds that global. It is compiled to plain JavaScript (asm.js), not WebAssembly, so it is ready as soon as it has loaded, with nothing to wait for. It is about 800 KB, 115 KB compressed.- Box2D simulates a flat world in the X–Y plane, in metres, kilograms and seconds, with Y up, like the world. Its
xandyare the box’s position in metres, under the Stack entity the script sits on, and its angle is the box’s rotation around Z; Z stays 0. Box2D works best with moving objects from 0.1 to 10 m across, so the boxes are 0.6 m. - The camera is orthographic, 6 m tall, looking along the Z axis: without perspective, each box shows as a flat square of the same size wherever it is, and the 3D scene reads as a 2D game.
startupmakes a Box2D body for each entity, from its position and rotation: the ground is static, the boxes are dynamic. The script steps only Box2D; the entities have no physics components of their own.- Box2D is stable with a fixed time step and jittery with a varying one, so
updateruns it in steps of 1/60 s, as many as the frame’sdeltacovers, then copies each body’s position and angle to its box. - box2d.js reads and writes fields through methods:
get_x(),set_type(…). Every object made withnew Box2D.…lives in Emscripten’s memory, which JavaScript’s garbage collector never frees:Box2D.destroyfrees the body definitions and shapes once Box2D has copied them, anddisposedestroys the world, and every body with it, when the script stops. SetAllowSleeping(true)lets Box2D stop simulating a body that has come to rest, which saves work in big scenes; a collision orSetAwake(true)wakes it. Each frame the script readsIsAwake()and turns a sleeping box blue and an awake one amber, callingsetPropsonly when the state changes.- Space puts each box back where it started, with a random tilt, and stops it.
SetAwake(true)wakes each one, so they turn amber again. - A click finds the box under the pointer with a
GraphicsRaycaster, which tests what is drawn: the boxes have no colliders for aPhysicsRaycasterto hit.ApplyLinearImpulsegives that box’s body an upward impulse of its mass times 4 m/s, at the point clicked, so it hops about 0.8 m and turns a little; its last argument wakes a sleeping box.
Snippets
Section titled “Snippets”1. Drifting platforms with simplex noise
Section titled “1. Drifting platforms with simplex noise”A realistic use of a URL import: a noise function makes several floating platforms drift smoothly and differently.
#pragma import(createNoise2D="https://cdn.jsdelivr.net/npm/simplex-noise@4.0.3/+esm")#pragma slot(ref=amplitude, type=Number, min=0, max=5, default=0.4)#pragma slot(ref=frequency, type=Number, min=0.01, max=5, default=0.3)#pragma lifecycle(startup, update)
const noise2D = createNoise2D();let platforms = [];let bases = [];
function startup() { platforms = self.parent.children.filter((child) => isEntity(child) && child !== self); bases = platforms.map((platform) => platform.position.y);}
function update(dt, time) { platforms.forEach((platform, i) => { platform.position.y = bases[i] + noise2D(i * 10, time * frequency) * amplitude; });}How it works:
#pragma import(createNoise2D="…")loads the module before the script runs and binds itscreateNoise2Dexport, so top-level code can call it at once.- The version is pinned in the URL, so the browser caches it, and every other script importing the same URL shares the download.
startupcollects the parent’s child entities, leaving out this Behavior entity, and remembers their starting heights.noise2D(i * 10, time * frequency)gives each platform its own smooth curve.
2. Confetti over the whole window
Section titled “2. Confetti over the whole window”canvas-confetti fires a burst of confetti.
#pragma import(confetti="https://cdn.jsdelivr.net/npm/canvas-confetti@1.9.3/+esm")#pragma lifecycle(startup)
function startup() { on('goal/scored', () => { confetti({ particleCount: 120, spread: 70, origin: { y: 0.6 } }); });}- The module has only a default export, so the single name
confettibinds it. - A library runs as ordinary page code, outside the script’s sandbox. canvas-confetti draws on a canvas of its own laid over the whole browser window, not inside the 3D view: in an embedded world it covers the page around it too, and in a headset it is not seen.
3. A chart on a texture
Section titled “3. A chart on a texture”Chart.js draws charts on a canvas. A script has no document to make one, but Canvas.create gives it a canvas, and Canvas.texture shows that canvas in the world.
#pragma import([Chart, registerables]="https://cdn.jsdelivr.net/npm/chart.js@4.4.4/+esm")#pragma lifecycle(startup)
function startup() { Chart.register(...registerables); const canvas = Canvas.create(512, 256); new Chart(canvas, { type: 'bar', data: { labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'], datasets: [{ label: 'Visitors', data: [12, 19, 7, 15, 22], backgroundColor: '#f59e0b' }], }, options: { responsive: false, animation: false }, }); const board = new THREE.Mesh( new THREE.PlaneGeometry(2, 1), new THREE.MeshBasicMaterial({ map: Canvas.texture(canvas) }), ); board.position.y = 1.5; self.parent.add(board);}Chart.register(...registerables)registers every chart type, scale and element; Chart.js draws nothing without it.- The canvas is not on the page, so the chart cannot resize with it or answer the pointer:
responsive: falsekeeps its size fixed, andanimation: falsedraws it at once, before the texture is made. - To change the chart, update its data, call
chart.update(), and setneedsUpdate = trueon the texture. See Canvas.
Common mistakes
Section titled “Common mistakes”An unpinned version
Section titled “An unpinned version”https://cdn.jsdelivr.net/npm/simplex-noise/+esm may change under you and is harder to cache. Name an exact version, as in every example on this page.
The wrong export name
Section titled “The wrong export name”A single name binds the export of that name, a global, or the default export. A name that matches none of them fails: #pragma import(Faker="…/@faker-js/faker@9.9.0/+esm") finds nothing, because the export is faker. Check the library’s documentation for its export names.
Listing names a module does not export
Section titled “Listing names a module does not export”#pragma import([Chart, registerAll]="https://cdn.jsdelivr.net/npm/chart.js@4.4.4/+esm")#pragma import([Chart, registerables]="https://cdn.jsdelivr.net/npm/chart.js@4.4.4/+esm")Each name in a list must be a named export: a list never falls back to the default export.
Reading the failed load message
Section titled “Reading the failed load message”When a library cannot be loaded or a name is not found, the script stops before it runs, with a message such as Failed to import URL https://…: The URL does not exist or the symbol [Faker] is not defined. Check, in that order: that the URL opens in a browser tab, that the version exists, and that the name in brackets is one the module exports.