---
title: Embed the viewer
summary: Put a Viewer3d in a page, load a model and know when it is fully loaded; where the viewer's modules come from, calling the API from another origin and switching web workers on.
order: 10
languages: [javascript]
terms: [viewer, model-manager, object-state-manager, version, vid]
see-also: [how-to/install/javascript, tutorials/javascript-viewer/embed-the-viewer, reference/viewer3d, explanation/geometry-and-the-viewers]
---

# Embed the viewer

This guide creates one 3D viewer in a page and loads one model version into it. To run the WebGPU viewer where the browser can and this one elsewhere, with the same code, see [[page:how-to/viewer3d/choose-the-viewer]].

## Before you start

You need the version UUID ([[term:vid|Vid]]) of a processed model and a token with at least `fs:read`, `geometry:read` and `query:run` on it (`addModels` queries the version's objects and storeys while it loads it). Install the packages from the registry ([[page:how-to/install/javascript]]).

## Steps

1. **Create the client and the two managers.** The factory is long-lived; the client can be too.
2. **Create the viewer, initialise it and put its container in the page.** `initializeViewer()` must have resolved before any other call on the viewer. The viewer sizes itself to its container, so give the container a size (flex, or an explicit width and height).
3. **Load the version.** `getNodeVersion` returns the complete `Version` object the viewer needs; `addModels` resolves when every connected component has finished loading it, so after the `await` the model is fully on screen.

```javascript {#embed}
import {BimWorksClientFactory} from "@bimworks/jssdk";
import {ModelManager, ObjectStateManager} from "@bimworks/viewercommon";
import {Viewer3d} from "@bimworks/viewer3d";

const factory = new BimWorksClientFactory(BIM_WORKS_ADDRESS);
const client = await factory.createClientWithApiToken(BIM_WORKS_API_TOKEN);

const modelManager = new ModelManager(client);
const objectStateManager = new ObjectStateManager(modelManager);

const viewer = new Viewer3d(objectStateManager, undefined, {
	technologyAllowed: {webGl2: true, webWorker: true, sharedArrayBuffer: true, transferable: true}
});
await viewer.initializeViewer();
document.getElementById("viewer").appendChild(viewer.container);

const version = await client.fs.getNodeVersion(BIM_WORKS_FIRST_MODEL);
await modelManager.addModels([version]);
// The model is completely loaded here
```

```warning
The example logs in with an API token to stay short. Do that only in a page nobody else opens: whoever loads the page can read the token. A page your users open gets a short-lived versions token from your backend and creates its client with `createClientWithAuth`, as [[page:how-to/viewer3d/show-your-users-models]] shows.
```

`addModels` throws `IncompleteVersionError` when the version has no `im_metadata` yet, which is the case while the server is still processing it or when you pass a summary object from a listing instead of the result of `getNodeVersion`.

## Progress, unloading and clean-up

- The second constructor argument is a `LoadProgressHandler` with optional `versionLoadProgress(version, percentage)`, `versionLoaded(version)` and `versionUnloaded(version)` methods.
- Unload with `modelManager.removeModels([version])`, never with `viewer.removeModels`: the ModelManager keeps its own list, and a version it still thinks is loaded is silently skipped by the next `addModels`.
- `viewer.stop()` pauses rendering while the viewer is hidden and `viewer.start()` resumes it; `viewer.destroy()` releases the GPU resources when the viewer goes away. `viewer.toggleAnimationEnabled()` starts and stops the slow rotation around the model (the Space key does the same).

## Load the models before the viewer {#models-first}

The order above is the usual one, but the ModelManager does not need a viewer. A page can load the models first, for instance while it is still building its layout, and create the viewer later: a viewer created on an ObjectStateManager whose ModelManager already holds models loads them itself.

```javascript {#models-first-snippet}
const modelManager = new ModelManager(client);
const objectStateManager = new ObjectStateManager(modelManager);
await modelManager.setModels([await client.fs.getNodeVersion(BIM_WORKS_FIRST_MODEL)]);

// Later: the new viewer loads what the ModelManager holds
const viewer = new Viewer3d(objectStateManager, {
	versionLoaded: (version) => console.log(version.node_name + " is on screen")
});
await viewer.initializeViewer();
document.getElementById("viewer").appendChild(viewer.container);
```

The viewer starts that load from its constructor and nothing returns its promise, so `versionLoaded` of the progress handler is the way to know the model is on screen. A second viewer on the same ObjectStateManager, a 2D viewer included, picks up the loaded models the same way; with the WebGPU viewer, a second 3D viewer on the same ModelManager shares them instead of loading them again ([[page:how-to/viewer3d/several-viewports]]).

With two viewers on one ModelManager, `addModels` and `setModels` hand the new models to the viewers one at a time, in the order the viewers were created, and resolve once the last one has them. Two WebGPU 3D viewers share one load, so the second has the models when the first does. With viewers that each load their own copy (the WebGL viewer, a 2D viewer), `modelManager.prioritizeOver(high, low)` puts viewer `high` ahead of viewer `low`, so the view the user is looking at gets its geometry first. Call it again when the other view comes to the front; both viewers must exist, and nothing changes when `high` is already first.

## Same origin, module URLs and workers

**The modules come from the npm packages.** An instance serves its own application as bundled files with content-hashed names, not the packages, so a page cannot import `Viewer3d` from the instance. Bundle the npm packages into your application or serve them from your own site ([[page:how-to/install/javascript]]). Bare specifiers such as `@bimworks/viewer3d` resolve only through a bundler or an import map, in an inline `<script type="module">` as in a file.

**The API from another origin.** A page on another origin than the instance calls the API cross-origin, and the instance's `web_security.cors` setting decides whether that is allowed. With the default, `WILDCARD`, every origin may call it and the CORS lists of API tokens are not consulted; `OPTIONAL` allows every origin as well. With `REQUIRED`, the origin must be on the CORS list of an active API token, and a call made after an API token login must come from an origin on that token's own list when the list has entries. The token's *Only allow certain CORS domains* switch is not checked by itself; only the list counts.

**Workers are off by default.** Without `technologyAllowed`, the viewer runs everything on the main thread (`{webGl2: true}` and nothing else). Switch on `webWorker`, `sharedArrayBuffer` and `transferable` as in the example for a smooth viewer; `sharedArrayBuffer` only takes effect on a cross-origin-isolated page (the `Cross-Origin-Opener-Policy` and `Cross-Origin-Embedder-Policy` headers), which is what the BIM.works pages themselves send. Some bundlers need configuration before the worker scripts resolve; if the viewer fails to start under Vite or webpack, `webWorker: false` is the quickest way to tell whether that is the cause.

## Check

The model is visible and reacts to the mouse ([[page:how-to/using-bimworks/navigate-the-3d-viewer]]); `modelManager.getVersions().size` is `1`.
