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.
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{
functioneffect(
setup:EffectSetup<Empty>
):Effect<Empty>(+2overloads)
Short form of defineEffect: defaults, optional options, setup. An unnamed effect takes its
registry key (the file name when a build plugin finds it).
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.
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.
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.
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.
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.
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.
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.
The page below shows a bar while the first screen loads, locks scroll and fades the preloader out once everything is ready.
index.html
<divid="preloader">
<divid="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{
functionready(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,
functionstart(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.
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).
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.
The HTMLElement interface represents any HTML element. Some elements directly implement this interface, while others implement it via an interface that inherits it.
The HTMLElement interface represents any HTML element. Some elements directly implement this interface, while others implement it via an interface that inherits it.
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()
asyncfunction
functionboot():Promise<void>
boot():
interfacePromise<T>
Represents the completion of an asynchronous operation
Promise<void>{
try{
await
functionready(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.
// 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()
constoff:()=>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.
The addEventListener() method of the EventTarget interface sets up a function that will be called whenever the specified event is delivered to the target.
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.
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.
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{
functionready(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,
functionstart(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.
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
functionready(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.