Diorama

Made for a big screen.

This site is one 3D scene, built for a computer: a wide window and a mouse. Open dioramajs.dev on a desktop or a laptop to see it.This site is one 3D scene, built for a wide window. Make this one wider, or open dioramajs.dev on a larger screen.

GitHub

DioramaDocs

Loading and preloading

Share one cache for images and models, preload the next page on intent, and drive a preloader from the progress of the first screen.

View as Markdown
On this page

Every image an effect shows, every model and every preload goes through one cache with progress. This guide covers what the cache keeps, how to preload the next page and how to build a preloader with a scroll lock.

The cache

start() adds the cache, and effects use it without code. The same URL decodes once, however many effects show it. An entry lives while something holds a lease on it; when the last lease goes, the entry stays for reuse up to retain bytes, 32 MB by default, and the least recently used go first. A model or cover seen on the previous page comes back without a request.

Inside an effect, load through the context: ctx.texture(url) for a texture and ctx.model(url) for a glTF. Their leases end with the effect, so nothing leaks when the element leaves.

src/effects/paper.ts
import {
function effect(
setup: EffectSetup<Empty>
): Effect<Empty> (+2 overloads)

Short form of defineEffect: defaults, optional options, setup. An unnamed effect takes its registry key (the file name when a build plugin finds it).

export default effect({ strength: 1 }, ({ surface, u }) => { ... })

effect
} from '@dioramajs/diorama'
import {
const texture: {
(
value?: Texture | TextureNode,
uvNode?: Node | null,
levelNode?: Node | number | null,
biasNode?: Node | null
): TextureNode;
<TNodeType>(
value?: Texture | TextureNode,
uvNode?: Node | null,
levelNode?: Node | number | null,
biasNode?: Node | null
): TextureNode<TNodeType>;
}
texture
as
const sample: {
(
value?: Texture | TextureNode,
uvNode?: Node | null,
levelNode?: Node | number | null,
biasNode?: Node | null
): TextureNode;
<TNodeType>(
value?: Texture | TextureNode,
uvNode?: Node | null,
levelNode?: Node | number | null,
biasNode?: Node | null
): TextureNode<TNodeType>;
}
sample
,
const uv: (index?: number) => AttributeNode<"vec2">
uv
} from 'three/tsl'
export default
effect<P>(
params: P & CheckSpec<P>,
setup: EffectSetup<ColorsIn<P>>
): Effect<WidenSpec<P>> (+2 overloads)
type P = {
readonly grain: 0.2;
}

Short form of defineEffect: defaults, optional options, setup. An unnamed effect takes its registry key (the file name when a build plugin finds it).

export default effect({ strength: 1 }, ({ surface, u }) => { ... })

effect
(
{
grain: 0.2
grain
: 0.2 },
async ({
surface: Surface

The shared GL copy of the element, created on first access.

surface
,
texture: (
url: string,
options?: TextureOptions
) => Promise<Texture>

A texture from the assets cache: shared, never dispose it. The lease dies with the phase. Needs assets.

texture
,
u: Uniforms<ColorsIn<{
readonly grain: 0.2;
}>>

Input uniforms and one uniform per live param, for TSL graphs.

u
}) => {
const
const noise: Texture<unknown, TextureEventMap>
noise
= await
texture: (
url: string,
options?: TextureOptions
) => Promise<Texture>

A texture from the assets cache: shared, never dispose it. The lease dies with the phase. Needs assets.

texture
('/textures/paper.avif', {
TextureOptions.colorSpace?:
| "srgb"
| "linear"
| undefined

Default 'srgb'. Depth maps and noise are 'linear'.

colorSpace
: 'linear',
})
surface: Surface

The shared GL copy of the element, created on first access.

surface
.
Surface.color(
transform: (color: Node<"vec4">, input: SurfaceInput) => Node
): Off

Changes the colour. sample(uv) reads the element's media with crop and masks applied.

color
((
color: Node<"vec4">
color
) =>
color: Node<"vec4">
color
.
mul: (
b: Vec4OrLessOrNumberParameterForNumType<"float">,
...params: Vec4OrLessOrNumberParameterForNumType<"float">[]
) => Node<"vec4"> (+4 overloads)
mul
(
function sample(
value?: Texture | TextureNode,
uvNode?: Node | null,
levelNode?: Node | number | null,
biasNode?: Node | null
): TextureNode (+1 overload)
sample
(
const noise: Texture<unknown, TextureEventMap>
noise
,
function uv(index?: number): AttributeNode<"vec2">
uv
()).
Swizzle1From1<"float">.r: Node<"float">
r
.
mul: (
b: NumberParameterForNumType<"float">,
...params: NumberParameterForNumType<"float">[]
) => Node<"float"> (+7 overloads)
mul
(
u: Uniforms<ColorsIn<{
readonly grain: 0.2;
}>>

Input uniforms and one uniform per live param, for TSL graphs.

u
.
grain: UniformNode<"float">
grain
).
FloatOrVecExtensions<"float">.oneMinus: () => Node<"float">
oneMinus
()),
)
},
)

Outside effects, app.assets.load(url) returns a lease at once. The type comes from the extension, or from type: image, texture, gltf, ktx2, buffer or json.

const
const data: Asset<unknown, AssetError>
data
=
const app: App
app
.
Services.assets: AssetsApi

Asset cache and preloading, see AssetsApi.

assets
.
AssetsApi.load<"json">(
url: string,
options: LoadOptions<"json"> & { readonly type: "json"; }
): Asset<unknown, AssetError> (+1 overload)

Loads a URL and returns a lease at once. The type comes from type or the extension. Never throws: ready rejects with an AssetError, ASSET_TYPE for an unknown type, ASSET_LOAD for a network or HTTP failure, ASSET_PARSE or ASSET_DECODER for bad data.

load
('/data/stations.json', {
type: "json"

Guessed from the extension when omitted: gltf for .glb and .gltf, ktx2 for .ktx2, texture for images.

type
: 'json' })
const
const stations: unknown
stations
= await
const data: Asset<unknown, AssetError>
data
.
Asset<unknown, AssetError>.ready: Promise<unknown>

Rejects with E, or with an unreported ASSET_ABORTED if released before ready.

ready
// Later, when the page no longer needs it:
const data: Asset<unknown, AssetError>
data
.
Asset<unknown, AssetError>.release(): void

Releases the lease. The entry goes when its last lease does.

release
()

ready rejects with ASSET_LOAD, ASSET_PARSE, ASSET_TYPE or ASSET_DECODER; the same failure is reported once through the app. ready(app) from @dioramajs/diorama resolves when the app runs, so app.assets exists.

Preload the next page on intent

Put the files of the next page in data-dio-preload on the link, separated by spaces. Hovering the link for 65 ms, focusing it or touching it puts them in the cache, so the cover is decoded by the time the flight lands.

work.html
<a
href="/work/aurora"
data-dio-preload="/img/aurora-cover.avif /models/aurora.glb"
>
<img
src="/img/aurora-thumb.avif"
data-dio="image"
data-dio-key="aurora"
/>
</a>

Images from another origin that the page shows with crossorigin must be preloaded in the same CORS mode, or the cache misses and the cover loads twice. Add crossorigin to the link; models in the same list load as usual.

<a
href="/work/aurora"
data-dio-preload="https://cdn.example.com/aurora.avif"
crossorigin
>Aurora</a>

Under Save-Data and on 2G connections nothing preloads.

Preload from router code

When the router has already fetched the next page, pass its document to app.assets.preload(). It takes the images with data-dio or data-dio-key and the URLs in data-dio-preload. An image inside <picture> picks the same source and size the new page picks.

const
const html: string
html
= await (await
function fetch(
input: RequestInfo | URL,
init?: RequestInit
): Promise<Response>
fetch
(
const url: "/work/aurora"
url
)).
Body.text(): Promise<string>
text
()
const
const next: Document
next
= new
var DOMParser: new () => DOMParser

The DOMParser interface provides the ability to parse XML or HTML source code from a string into a DOM Document.

MDN Reference

DOMParser
().
DOMParser.parseFromString(
string: string,
type: DOMParserSupportedType
): Document

The parseFromString() method of the DOMParser interface parses an input containing either HTML or XML, returning a Document with the type given in the contentType property.

MDN Reference

parseFromString
(
const html: string
html
, 'text/html')
const app: App
app
.
Services.assets: AssetsApi

Asset cache and preloading, see AssetsApi.

assets
.
AssetsApi.preload(
source: PreloadSource,
options?: PreloadOptions
): Preload

Next page's media and models: URLs, a parsed Document (Astro, Swup) or a container (Barba).

preload
(
const next: Document
next
, {
PreloadOptions.base?: string | URL | undefined

Base for relative URLs and srcset, i.e. the next page's URL. Defaults to , then document.baseURI.

base
:
const url: "/work/aurora"
url
})

Pass the URL of the next page as base. A parsed document has the address of the current page, so img/cover.avif on /work/aurora/ would otherwise resolve against /work. A page URL is not an asset: preload('/work/aurora') warns with ASSET_TYPE in development.

  • Only the latest preload of each kind is held: one from markup and one from code. The previous one is released, and its entries stay in the cache within retain.
  • Preloads run at low priority and wait while a flight is in the air, so the flight’s frames stay smooth. A cover the landing target already needs decodes at once.
  • A failed preload does nothing visible: the page loads the file itself and reports a failure then.

The routers guide has the preload line for Astro and Swup.

Progress of the first screen

app.assets.progress is a signal from 0 to 1 for the current wave of work. During start() effects put their first screen into it: the engine, the renderer and the images of effects near the viewport. Models and textures loaded at normal or high priority join the wave; preloads do not move it. Within a wave progress never goes back, and it reaches 1 when app.assets.ready() resolves.

Add your own work to the wave with track(), for example web fonts. weight is in bytes, 100 000 by default.

const app: App
app
.
Services.assets: AssetsApi

Asset cache and preloading, see AssetsApi.

assets
.
AssetsApi.track(
work: PromiseLike<unknown>,
options?: {
readonly weight?: number;
readonly priority?: Priority;
}
): void

Counts outside work in the current wave, like first-screen effects, fonts or page HTML. weight: 0 holds ready() without moving progress or starting a wave of its own.

track
(
var document: Document

window.document returns a reference to the document contained in the window.

MDN Reference

document
.
FontFaceSource.fonts: FontFaceSet
fonts
.
FontFaceSet.ready: Promise<FontFaceSet>

The ready read-only property of the FontFaceSet interface returns a Promise that resolves to the given FontFaceSet.

MDN Reference

ready
, {
weight?: number | undefined
weight
: 60_000 })

Build a preloader

The page below shows a bar while the first screen loads, locks scroll and fades the preloader out once everything is ready.

index.html
<div id="preloader">
<div id="bar"></div>
</div>
src/preloader.css
html.is-loading {
overflow: hidden;
}
#preloader {
position: fixed;
inset: 0;
z-index: 10;
display: grid;
place-items: center;
background: #0b0b10;
transition: opacity 0.6s;
}
#bar {
width: 40vw;
height: 2px;
background: #f4efe6;
transform: scaleX(0);
transform-origin: left;
}
src/main.ts
import {
function ready(app?: App): Promise<App>

Resolves with the app once it runs: the page's app of start() by default, waiting for the call if it has not happened yet. Rejects if the app fails or is destroyed first.

const app = await ready()
app.effects.get(el, 'ripple')

ready
,
function start(options?: StartOptions): App

Starts Diorama on the page and returns the app at once. It finishes starting in the background. A second call returns the same app, so a re-run module doesn't make another.

import { start } from '@dioramajs/diorama'
export const app = start()

start
} from '@dioramajs/diorama'
const
const root: HTMLElement
root
=
var document: Document

window.document returns a reference to the document contained in the window.

MDN Reference

document
.
Document.documentElement: HTMLElement

The documentElement read-only property of the Document interface returns the Element that is the root element of the document (for example, the element for HTML documents).

MDN Reference

documentElement
const root: HTMLElement
root
.
Element.classList: DOMTokenList

The read-only classList property of the Element interface contains a live DOMTokenList collection representing the class attribute of the element. This can then be used to manipulate the class list.

MDN Reference

classList
.
DOMTokenList.add(...tokens: string[]): void

The add() method of the DOMTokenList interface adds the given tokens to the list, omitting any that are already present.

MDN Reference

add
('is-loading')
const
const preloader: HTMLElement | null
preloader
=
var document: Document

window.document returns a reference to the document contained in the window.

MDN Reference

document
.
ParentNode.querySelector<HTMLElement>(selectors: string): HTMLElement
| null (+4 overloads)

Returns the first element that is a descendant of node that matches selectors.

MDN Reference

querySelector
<
interface HTMLElement

The HTMLElement interface represents any HTML element. Some elements directly implement this interface, while others implement it via an interface that inherits it.

MDN Reference

HTMLElement
>('#preloader')
const
const bar: HTMLElement | null
bar
=
var document: Document

window.document returns a reference to the document contained in the window.

MDN Reference

document
.
ParentNode.querySelector<HTMLElement>(selectors: string): HTMLElement
| null (+4 overloads)

Returns the first element that is a descendant of node that matches selectors.

MDN Reference

querySelector
<
interface HTMLElement

The HTMLElement interface represents any HTML element. Some elements directly implement this interface, while others implement it via an interface that inherits it.

MDN Reference

HTMLElement
>('#bar')
export const
const app: App
app
=
function start(options?: StartOptions): App

Starts Diorama on the page and returns the app at once. It finishes starting in the background. A second call returns the same app, so a re-run module doesn't make another.

import { start } from '@dioramajs/diorama'
export const app = start()

start
()
async function
function boot(): Promise<void>
boot
():
interface Promise<T>

Represents the completion of an asynchronous operation

Promise
<void> {
try {
await
function ready(app?: App): Promise<App>

Resolves with the app once it runs: the page's app of start() by default, waiting for the call if it has not happened yet. Rejects if the app fails or is destroyed first.

const app = await ready()
app.effects.get(el, 'ripple')

ready
(
const app: App
app
)
const app: App
app
.
Services.assets: AssetsApi

Asset cache and preloading, see AssetsApi.

assets
.
AssetsApi.track(
work: PromiseLike<unknown>,
options?: {
readonly weight?: number;
readonly priority?: Priority;
}
): void

Counts outside work in the current wave, like first-screen effects, fonts or page HTML. weight: 0 holds ready() without moving progress or starting a wave of its own.

track
(
var document: Document

window.document returns a reference to the document contained in the window.

MDN Reference

document
.
FontFaceSource.fonts: FontFaceSet
fonts
.
FontFaceSet.ready: Promise<FontFaceSet>

The ready read-only property of the FontFaceSet interface returns a Promise that resolves to the given FontFaceSet.

MDN Reference

ready
)
const
const off: Off
off
=
const app: App
app
.
Services.assets: AssetsApi

Asset cache and preloading, see AssetsApi.

assets
.
AssetsApi.progress: ReadonlySignal<number>

Progress of the current wave of high and normal work, 0..1. Never goes back within a wave.

progress
.
ReadonlySignal<number>.subscribe(
listener: (value: number) => void
): Off

Calls the listener now and after every change (Svelte store contract).

subscribe
((
p: number
p
) => {
if (
const bar: HTMLElement | null
bar
)
const bar: HTMLElement
bar
.
ElementCSSInlineStyle.style: CSSStyleDeclaration
style
.
CSSStyleProperties.transform: string

The transform CSS property lets you rotate, scale, skew, or translate an element. It modifies the coordinate space of the CSS visual formatting model.

MDN Reference

transform
= `scaleX(${
p: number
p
})`
})
// The engine, first-screen images, models and fonts. Never rejects.
await
const app: App
app
.
Services.assets: AssetsApi

Asset cache and preloading, see AssetsApi.

assets
.
AssetsApi.ready(): Promise<void>

Settles when the current wave is done, or at once without one. Failures count as done.

ready
()
const off: () => void
off
()
} finally {
// Unlock even if the app fails: the page works as plain HTML.
const root: HTMLElement
root
.
Element.classList: DOMTokenList

The read-only classList property of the Element interface contains a live DOMTokenList collection representing the class attribute of the element. This can then be used to manipulate the class list.

MDN Reference

classList
.
DOMTokenList.remove(...tokens: string[]): void

The remove() method of the DOMTokenList interface removes the specified tokens from the list.

MDN Reference

remove
('is-loading')
const preloader: HTMLElement | null
preloader
?.
HTMLElement.addEventListener<K>(
type: K,
listener: (
this: HTMLElement,
ev: HTMLElementEventMap[K]
) => any,
options?: boolean | AddEventListenerOptions
): void (+1 overload)

The addEventListener() method of the EventTarget interface sets up a function that will be called whenever the specified event is delivered to the target.

MDN Reference

addEventListener
(
'transitionend',
() =>
const preloader: HTMLElement
preloader
.
ChildNode.remove(): void

Removes node.

MDN Reference

remove
(),
{
AddEventListenerOptions.once?: boolean | undefined
once
: true },
)
if (
const preloader: HTMLElement | null
preloader
)
const preloader: HTMLElement
preloader
.
ElementCSSInlineStyle.style: CSSStyleDeclaration
style
.
CSSStyleProperties.opacity: string

The opacity CSS property sets the opacity of an element. Opacity is the degree to which content behind an element is hidden, and is the opposite of transparency.

MDN Reference

opacity
= '0'
}
}
void
function boot(): Promise<void>
boot
()

Live preview needs WebGPU or WebGL 2. A preloader over three prints: once the engine is ready its bar fills a third for each print that arrives over a slow network, then the preloader fades out.

This example failed to draw.

The example reads the images at 48 KB a second, as a slow network would.

import { ready } from '@dioramajs/diorama'
import { app } from '../../docs/diorama.ts'
const IMAGES = [
'/media/prints/dawn.jpg',
'/media/prints/dusk.jpg',
'/media/prints/night.jpg',
]
// Stands in for a slow network: every body is read at 48 KB a second, all of them in turn.
const RATE = 48_000
let line = Promise.resolve()
async function slowBlob(url: string): Promise<Blob> {
const response = await fetch(url)
const reader = response.body?.getReader()
const chunks: Uint8Array<ArrayBuffer>[] = []
for (
let read = await reader?.read();
read && !read.done;
read = await reader?.read()
) {
const chunk = read.value
line = line.then(
() =>
new Promise((done) =>
setTimeout(done, (chunk.length / RATE) * 1000),
),
)
await line
chunks.push(chunk)
}
return new Blob(chunks, {
type: response.headers.get('content-type') ?? 'image/jpeg',
})
}
async function addImage(shots: Element, url: string): Promise<void> {
const img = document.createElement('img')
img.alt = ''
img.src = URL.createObjectURL(await slowBlob(url))
shots.append(img)
await img.decode()
}
// src/main.ts of the guide, run on the box of the example instead of the whole page.
export default (example: HTMLElement) => {
const preloader = example.querySelector<HTMLElement>('#preloader')
const bar = example.querySelector<HTMLElement>('#bar')
const shots = example.querySelector('.shots')
const again = example.querySelector('.again')
if (!preloader || !bar || !shots) return
async function boot(): Promise<void> {
try {
await ready(app)
// The weight is in bytes, about the size of each print.
for (const url of IMAGES)
app.assets.track(addImage(shots as Element, url), {
weight: 45_000,
})
const off = app.assets.progress.subscribe((p) => {
if (bar) bar.style.transform = `scaleX(${p})`
})
// The engine and the three prints. Never rejects.
await app.assets.ready()
off()
} finally {
if (preloader) preloader.style.opacity = '0'
}
}
const replay = () => {
for (const img of shots.querySelectorAll('img')) {
URL.revokeObjectURL(img.src)
img.remove()
}
preloader.style.transition = 'none'
preloader.style.opacity = '1'
bar.style.transform = 'scaleX(0)'
void preloader.offsetWidth
preloader.style.transition = ''
void boot()
}
again?.addEventListener('click', replay)
void boot()
return () => again?.removeEventListener('click', replay)
}
<div class="page">
<div class="shots"></div>
<div id="preloader">
<div id="bar"></div>
</div>
</div>

Without WebGPU or WebGL 2, or under Save-Data, the engine does not load and the wave ends at once, so the preloader does not hang.

With Lenis, overflow: hidden on the root does not stop wheel scrolling. Stop Lenis instead and start it in the same finally.

import {
function ready(app?: App): Promise<App>

Resolves with the app once it runs: the page's app of start() by default, waiting for the call if it has not happened yet. Rejects if the app fails or is destroyed first.

const app = await ready()
app.effects.get(el, 'ripple')

ready
,
function start(options?: StartOptions): App

Starts Diorama on the page and returns the app at once. It finishes starting in the background. A second call returns the same app, so a re-run module doesn't make another.

import { start } from '@dioramajs/diorama'
export const app = start()

start
} from '@dioramajs/diorama'
import
class Lenis
Lenis
from 'lenis'
const
const lenis: Lenis
lenis
= new
new Lenis(
{
wrapper, content, eventsTarget, smoothWheel, syncTouch,
syncTouchLerp, touchInertiaExponent, duration, easing, lerp,
infinite, orientation, gestureOrientation, touchMultiplier,
wheelMultiplier, autoResize, prevent, virtualScroll,
overscroll, autoRaf, anchors, autoToggle, allowNestedScroll,
__experimental__naiveDimensions, naiveDimensions,
stopInertiaOnNavigate, respectReducedMotion
}?: LenisOptions
): Lenis
Lenis
()
export const
const app: App
app
=
function start(options?: StartOptions): App

Starts Diorama on the page and returns the app at once. It finishes starting in the background. A second call returns the same app, so a re-run module doesn't make another.

import { start } from '@dioramajs/diorama'
export const app = start()

start
({
StartOptions.lenis?: LenisLike | undefined

The site's Lenis instance, so smooth scroll lands in the same frame as the canvas.

lenis
})
const lenis: Lenis
lenis
.
Lenis.stop(): void

Stop lenis scroll

stop
()
await
function ready(app?: App): Promise<App>

Resolves with the app once it runs: the page's app of start() by default, waiting for the call if it has not happened yet. Rejects if the app fails or is destroyed first.

const app = await ready()
app.effects.get(el, 'ripple')

ready
(
const app: App
app
)
.
Promise<App>.then<void, never>(
onfulfilled?:
| ((value: App) => void | PromiseLike<void>)
| null
| undefined,
onrejected?:
| ((reason: any) => PromiseLike<never>)
| null
| undefined
): Promise<void>

Attaches callbacks for the resolution and/or rejection of the Promise.

@param ― onfulfilled The callback to execute when the Promise is resolved.

@param ― onrejected The callback to execute when the Promise is rejected.

@returns ― A Promise for the completion of which ever callback is executed.

then
(() =>
const app: App
app
.
Services.assets: AssetsApi

Asset cache and preloading, see AssetsApi.

assets
.
AssetsApi.ready(): Promise<void>

Settles when the current wave is done, or at once without one. Failures count as done.

ready
())
.
Promise<void>.finally(
onfinally?: (() => void) | null | undefined
): Promise<void>

Attaches a callback that is invoked when the Promise is settled (fulfilled or rejected). The resolved value cannot be modified from the callback.

@param ― onfinally The callback to execute when the Promise is settled (fulfilled or rejected).

@returns ― A Promise for the completion of the callback.

finally
(() =>
const lenis: Lenis
lenis
.
Lenis.start(): void

Start lenis scroll after it has been stopped

start
())

A bar without JavaScript

Mark any element with data-dio-progress and it gets the custom property --dio-progress. Diorama writes nothing else into it.

<div
data-dio-progress
style="transform: scaleX(var(--dio-progress, 0))"
></div>

The bar follows the page loading: the first wave, and the wave of each page change, from 0. Pictures that load later as the visitor scrolls move app.assets.progress but not the bar, so it never jumps back in the middle of a scroll.