Skip to content

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.

  • Modules: #pragma export and #pragma import(name) between scripts. A URL import shares their registry of names.
  • Directives: how a #pragma is written.
  • Behavior scripts: the sandbox a script runs in.

#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.

Charts.jx
#pragma import(confetti="https://cdn.jsdelivr.net/npm/[email protected]/+esm")
#pragma import([Chart, registerables]="https://cdn.jsdelivr.net/npm/[email protected]/+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:// or https://, 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.

A CDN URL names a package and, after an @, a version: https://cdn.jsdelivr.net/npm/[email protected]/+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.

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.

A list of names, [A, B]="url", binds each named export of one module:

#pragma import([forceSimulation, forceManyBody]="https://cdn.jsdelivr.net/npm/[email protected]/+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 find Chart.

Faker makes up realistic data: names, jobs, addresses, dates. Here it names three visitors, and R names them again.

VisitorBadges.jx
#pragma import(faker="https://cdn.jsdelivr.net/npm/@faker-js/[email protected]/+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();
}

How it works:

  • #pragma import(faker="…/@faker-js/[email protected]/+esm") binds the module’s faker export 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; \n breaks the name and the job onto two lines.

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.

ForceGraph.jx
#pragma import([forceSimulation, forceManyBody, forceLink, forceCenter]="https://cdn.jsdelivr.net/npm/[email protected]/+esm")
#pragma lifecycle(startup, update)
const SCALE = 0.02; // simulation units to metres
const 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;
}

How it works:

  • One pragma binds four named exports of the same module.
  • .stop() stops the simulation’s own timer. update calls simulation.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: SCALE turns its x and y into metres, and setPosition places 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.

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.

ConfettiBurst.jx
#pragma import(confetti="https://cdn.jsdelivr.net/npm/[email protected]/+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
}

How it works:

  • confetti.create(canvas, { resize: false }) returns a fire function bound to the script’s canvas; resize: false keeps the size Canvas.create gave it.
  • throttle makes burst run at most once every 500 ms, so holding or hammering Space cannot flood the canvas; each burst starts at a random x along 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’s aspect, so it fills the view, even when the window is resized.
  • The material is transparent, so only the confetti shows, and depthTest: false with a renderOrder draws it over everything in the scene.
  • canvas-confetti animates the canvas on its own; texture.needsUpdate = true sends each new frame to the texture.

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.

EdgeDetector.jx
#pragma import(cv="https://cdn.jsdelivr.net/npm/@techstark/[email protected]/dist/opencv.js")
#pragma lifecycle(startup, update)
const SIZE = 512;
const THRESHOLDS = [[50, 150], [100, 200], [20, 60]]; // Canny low and high
let 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();
}

How it works:

  • opencv.js is a classic script, not an ES module, so the loader adds it to the page and binds the cv it publishes. Its WebAssembly is inside the file, and cv is a promise that settles once the WebAssembly has started: the loader waits for it, so cv.Mat is ready when startup runs.
  • 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.js files of some other versions, such as 4.10.0 on docs.opencv.org, hand over a cv that the loader cannot wait for, and the page stops responding while it loads.
  • The script has no document to load an image with: THREE.ImageLoader loads the picture, and drawImage draws it on a canvas made with Canvas.create. willReadFrequently tells the browser that this canvas is read back often, by cv.imread.
  • cv.imread reads a canvas’s pixels into a cv.Mat, an image in OpenCV’s memory. cvtColor turns it gray, Canny keeps only the edges, and cv.imshow draws the result on the second canvas.
  • A cv.Mat lives 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 = true sends the new edges to the plane after each detection.

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.

FallingBoxes.jx
#pragma import(Box2D="https://cdn.jsdelivr.net/npm/[email protected]/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 too
const STEP = 1 / 60; // Box2D wants a fixed time step, in seconds
const AWAKE = '#f59e0b';
const ASLEEP = '#60a5fa'; // a body at rest that Box2D stopped simulating
const 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 Box2D
let 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);
}

How it works:

  • Box2D_v2.3.1_min.js is a classic script that sets a global Box2D, 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 x and y are 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.
  • startup makes 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 update runs it in steps of 1/60 s, as many as the frame’s delta covers, 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 with new Box2D.… lives in Emscripten’s memory, which JavaScript’s garbage collector never frees: Box2D.destroy frees the body definitions and shapes once Box2D has copied them, and dispose destroys 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 or SetAwake(true) wakes it. Each frame the script reads IsAwake() and turns a sleeping box blue and an awake one amber, calling setProps only 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 a PhysicsRaycaster to hit. ApplyLinearImpulse gives 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.

A realistic use of a URL import: a noise function makes several floating platforms drift smoothly and differently.

Drift.jx
#pragma import(createNoise2D="https://cdn.jsdelivr.net/npm/[email protected]/+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 its createNoise2D export, 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.
  • startup collects 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.

canvas-confetti fires a burst of confetti.

Celebrate.jx
#pragma import(confetti="https://cdn.jsdelivr.net/npm/[email protected]/+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 confetti binds 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.

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.

VisitorChart.jx
#pragma import([Chart, registerables]="https://cdn.jsdelivr.net/npm/[email protected]/+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: false keeps its size fixed, and animation: false draws it at once, before the texture is made.
  • To change the chart, update its data, call chart.update(), and set needsUpdate = true on the texture. See Canvas.

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.

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/[email protected]/+esm") finds nothing, because the export is faker. Check the library’s documentation for its export names.

Wrong
#pragma import([Chart, registerAll]="https://cdn.jsdelivr.net/npm/[email protected]/+esm")
Right
#pragma import([Chart, registerables]="https://cdn.jsdelivr.net/npm/[email protected]/+esm")

Each name in a list must be a named export: a list never falls back to the default export.

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.