---
title: "Switch documents in a JavaScript PDF viewer | Nutrient SDK"
canonical_url: "https://www.nutrient.io/guides/web/open-a-document/switch-documents/"
md_url: "https://www.nutrient.io/guides/web/open-a-document/switch-documents.md"
last_updated: "2026-12-02T00:00:00.000Z"
description: "Load another document into a mounted Nutrient Web SDK viewer with instance.load(). The instance, its event listeners, and UI customization stay in place."
---

# Switch documents without reloading the viewer

[`instance.load()`](https://www.nutrient.io/api/web/classes/NutrientViewer.Instance.html#load) loads another document into a viewer that’s already mounted. It keeps the viewer, the WebAssembly engine, and your viewer configuration in place while resetting document-specific state like page, zoom, and selection.

`instance.load()` is available in [Nutrient Web SDK 1.27.0](https://www.nutrient.io/guides/web/changelog.md#1.27.0) and later, in [standalone mode](https://www.nutrient.io/guides/web/about/operational-modes.md) only. It isn’t available in server-backed mode or with DWS Viewer API. For details, refer to the [limitations](#limitations) section.

## Load another document

Call `instance.load()` on the instance that [`NutrientViewer.load()`](https://www.nutrient.io/api/web/functions/NutrientViewer.load.html) returned:

```js
import NutrientViewer from "@nutrient-sdk/viewer";

async function openDocuments() {
  try {
    // Create the viewer once, with the first document.
    const instance = await NutrientViewer.load({
      container: "#pspdfkit",
      document: "/first.pdf"
    });

    // Register listeners once. They stay active after `instance.load()`.
    instance.addEventListener("annotations.create", (annotations) => {
      console.log(`Created ${annotations.size} annotations`);
    });

    // Load the next document into the same viewer.
    const sameInstance = await instance.load({ document: "/second.pdf" });

    console.log(sameInstance === instance); // true
  } catch (error) {
    console.error("Failed to load document:", error.message);
  }
}

openDocuments();
```

The promise resolves with the same instance, so you don’t need to store a new reference or register listeners again.

`instance.load()` accepts three keys from [`Configuration`](https://www.nutrient.io/api/web/interfaces/Configuration.html) and rejects any other key with an error naming the alternative:

| Key                | Description                                                                                                        |
| ------------------ | ------------------------------------------------------------------------------------------------------------------ |
| `document`         | Required. URL string or `ArrayBuffer` to load.                                                                     |
| `password`         | Optional. Password for a protected document. Refer to the [load password-protected documents](#load-password-protected-documents) section.           |
| `initialViewState` | Optional. Initial page, zoom, or layout for the new document. Refer to the [set the initial view state](#set-the-initial-view-state) section. |

Keep these rules in mind for `document`:

- URL loads reuse the `httpHeaders` from `NutrientViewer.load()`. Fetch the file in your app and pass an `ArrayBuffer` when the next document needs different headers.

- An `ArrayBuffer` transfers ownership to the viewer, even when the load fails. Copy it first with `buffer.slice(0)` if you want to retry.

- `Blob` inputs aren’t accepted. Convert them with `await blob.arrayBuffer()` first.

For the full type and key rules, refer to [`InstanceLoadConfiguration`](https://www.nutrient.io/api/web/interfaces/InstanceLoadConfiguration.html) in the API reference.

## Switch the document or reload the viewer

A viewer can show another document in two supported ways. `instance.load()` swaps the document in place while the viewer stays mounted. [`NutrientViewer.unload()`](https://www.nutrient.io/api/web/functions/NutrientViewer.unload.html) followed by `NutrientViewer.load()` tears down the viewer and creates a new one.

Switching in place gives you four main benefits over reloading:

- **No user interface (UI) flicker** — The toolbar and current document stay visible while the next file downloads.

- **No repeated setup** — The instance, event listeners, toolbar items, and custom UI stay attached.

- **Faster rapid browsing** — The SDK drops queued intermediate loads when users step rapidly through documents.

- **Safer failures** — Most failed loads leave the current document open instead of an empty error state.

| Area                                 | Switch the document                                                | Reload the viewer                                                                   |
| ------------------------------------ | ------------------------------------------------------------------ | ----------------------------------------------------------------------------------- |
| Viewer UI during the switch          | Stays onscreen while the next file downloads                       | Tears down and remounts the viewer DOM                                              |
| Instance, listeners, and UI          | Stay in place                                                      | Removed and set up again on a new instance                                          |
| Rapid requests                       | Queued by the SDK; drops intermediate loads so the latest wins     | Your app prevents overlap, or every click rebuilds the viewer                       |
| Failed load                          | Current document stays open in [most cases](#handle-failed-loads)   | No document stays open                                                              |
| Viewer configuration and annotations | Fixed viewer configuration; import Instant JSON or XFDF after load | Full configuration on each load, including `theme`, `httpHeaders`, and Instant JSON |
| Passwords and linearized PDFs        | App supplies password; downloads full URL first                    | Built-in password prompt; progressive first pages                                   |
| Mode and version                     | Standalone mode, 1.27 and later                                    | All modes and versions                                                              |

This fits tab-based UIs, document lists, and review queues. In a tabbed workspace, one mounted viewer serves every tab without mounting a viewer per tab or flickering the toolbar on each click. Pair it with [`initialViewState`](#set-the-initial-view-state) to restore each tab’s page and zoom, and [export unsaved changes](#save-and-export-changes-before-switching) before switching tabs.

Reload the viewer when the next document needs a different theme, load-time Instant JSON or XFDF, the built-in password prompt, or server-backed mode. For a reload example, refer to the [embed Web SDK in a dashboard/app shell](https://www.nutrient.io/guides/web/viewer/embed-in-dashboard-app-shell.md) guide. To show several documents at the same time, create one viewer per document with `NutrientViewer.load()`.

## What stays and what resets

A successful `instance.load()` updates viewer and document state as follows:

| State                                                                                                                      | After a switch                                                                                 | Override with initial view state |
| -------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | -------------------------------- |
| Instance, event listeners, toolbar items, annotation presets, theme, locale, custom UI, custom renderers, and open sidebar | Kept                                                                                           | No                               |
| Layout mode, scroll mode, page spacing, viewport padding, and zoom input settings                                          | Kept                                                                                           | Yes                              |
| Page index, zoom, and page rotation                                                                                        | Reset to first page, `ZoomMode.AUTO`, and no rotation                                          | Yes                              |
| Selection, search, interaction mode, undo history, and custom overlay items                                                | Cleared                                                                                        | No                               |
| Pages, annotations, form fields, comments, bookmarks, outline, embedded files, layers, signatures, and permissions         | Replaced by the new document                                                                   | No                               |
| AI Assistant, when configured                                                                                              | Restarted for the new document; keeps its `sessionId`, so the earlier conversation loads again | No                               |

Without `initialViewState`, the page index always resets to the first page because no rule maps a page of one document to another. Custom renderers stay registered and run again for the new document, so read document values inside the callback instead of capturing them earlier.

## Handle rapid switches

Calls to `instance.load()` on one instance run one at a time. While a load runs, only the newest waiting call stays queued. Any older waiting call is dropped without touching the viewer, and its promise rejects as superseded. Calling `NutrientViewer.unload()` while a load is running or waiting rejects the promise with an `AbortError`.

A superseded rejection is normal flow, not a failure. Add a `catch` handler to every `instance.load()` call and filter it with [`NutrientViewer.isDocumentLoadSupersededError()`](https://www.nutrient.io/api/web/functions/NutrientViewer.isDocumentLoadSupersededError.html) so fast clicks don’t produce unhandled promise rejections:

```js
import NutrientViewer from "@nutrient-sdk/viewer";

async function switchDocument(instance, url) {
  try {
    await instance.load({ document: url });
  } catch (error) {
    // A newer `instance.load()` call replaced this one before it started.
    if (NutrientViewer.isDocumentLoadSupersededError(error)) {
      return;
    }

    // The viewer was unloaded while this call was running or waiting.
    if (error.name === "AbortError") {
      return;
    }

    // A real failure. Report it, and show it in your UI.
    console.error(`Failed to load ${url}:`, error.message);
  }
}
```

## Handle failed loads

When the next document can’t open, `instance.load()` rejects. Pass the error to [`NutrientViewer.isPreviousDocumentClosedError()`](https://www.nutrient.io/api/web/functions/NutrientViewer.isPreviousDocumentClosedError.html) to check whether the previous document is still usable:

| Result  | What the user sees                                     |
| ------- | ------------------------------------------------------ |
| `false` | The current document stays open and usable             |
| `true`  | The viewer shows its error state with no open document |

`instance.load()` opens the new document before closing the current one, so most failures return `false`. That covers failed downloads, corrupted or unsupported files, failed Office conversions, wrong or missing passwords, and failed saves of pending changes. A `false` result still leaves the current document open, though a late failure can cancel a running print job or search. It can also close an open Content Editor without saving.

The function returns `true` in three cases:

- The new document uses origin private file system (OPFS) [temporary storage](https://www.nutrient.io/guides/web/open-a-document/temp-storage.md). That is the default (`"auto"`) for larger URL-loaded PDFs and closes the previous document first. Set [`tempStorage`](https://www.nutrient.io/api/web/interfaces/Configuration.html#tempstorage) to `"memory"` on `NutrientViewer.load()` to avoid it.

- The failure happens after the new document opens, while loading its pages, annotations, or form fields.

- The viewer is already showing an error state from an earlier failed load, and the next load fails too.

To recover when the previous document closed, call `instance.load()` again with a valid document, guarding against a newer switch:

```js
import NutrientViewer from "@nutrient-sdk/viewer";

const latestRequestByInstance = new WeakMap();

async function switchDocument(instance, url, previousUrl) {
  const requestId = (latestRequestByInstance.get(instance) ?? 0) + 1;
  latestRequestByInstance.set(instance, requestId);

  try {
    await instance.load({ document: url });
  } catch (error) {
    if (NutrientViewer.isDocumentLoadSupersededError(error)) {
      return;
    }

    if (error.name === "AbortError") {
      return;
    }

    console.error(`Failed to load ${url}:`, error.message);

    // No document is open anymore. Reload the previous one,
    // unless a newer switch was requested on this viewer.
    if (
      NutrientViewer.isPreviousDocumentClosedError(error) &&
      latestRequestByInstance.get(instance) === requestId &&
      previousUrl &&
      url !== previousUrl
    ) {
      await switchDocument(instance, previousUrl, previousUrl);
    }
  }
}
```

`document.swap` never fires for a failed load. Failures before the new document opens emit neither event. Failures after it opens can emit `document.willSwap` without `document.swap`, so restore any UI you cleared there in your `catch` block.

## Save and export changes before switching

`instance.load()` replaces the document in memory, so changes that aren’t exported are lost. What happens to pending changes before the switch depends on [`autoSaveMode`](https://www.nutrient.io/api/web/interfaces/Configuration.html#autosavemode):

- `AutoSaveMode.IMMEDIATE` (the standalone default) and `AutoSaveMode.INTELLIGENT` — The viewer saves pending changes into the outgoing document first. If saving fails, `instance.load()` rejects and the current document stays open.

- `AutoSaveMode.DISABLED` — The viewer discards unsaved changes.

- Unsaved Content Editor edits are discarded in every mode, so save or close the Content Editor before switching.

Saving in standalone mode writes changes to the in-memory document, not to your own storage. Call [`instance.save()`](https://www.nutrient.io/api/web/classes/NutrientViewer.Instance.html#save) and export with [`instance.exportPDF()`](https://www.nutrient.io/api/web/classes/NutrientViewer.Instance.html#exportpdf) or [`instance.exportInstantJSON()`](https://www.nutrient.io/api/web/classes/NutrientViewer.Instance.html#exportinstantjson) before calling `instance.load()`:

```js
import NutrientViewer from "@nutrient-sdk/viewer";

const switchQueueByInstance = new WeakMap();

function switchWithAnnotations(instance, nextUrl, storedInstantJSON) {
  const previous = switchQueueByInstance.get(instance) ?? Promise.resolve();

  // Serialize save, export, load, and import so document APIs never overlap a switch.
  const run = previous.then(async () => {
    let currentInstantJSON = null;

    try {
      await instance.save();
      currentInstantJSON = await instance.exportInstantJSON();

      await instance.load({ document: nextUrl });

      // Import the annotations that your app stored for the new document.
      if (storedInstantJSON) {
        await instance.applyOperations([
          { type: "applyInstantJson", instantJson: storedInstantJSON }
        ]);
      }
    } catch (error) {
      if (!NutrientViewer.isDocumentLoadSupersededError(error)) {
        console.error(`Failed to switch to ${nextUrl}:`, error.message);
      }
    }

    return currentInstantJSON;
  });

  switchQueueByInstance.set(
    instance,
    run.catch(() => {})
  );

  return run;
}
```

The queue wraps the full save, export, load, and import flow, because the SDK only serializes `instance.load()` itself. `instance.load()` doesn’t accept `instantJSON` or `XFDF`, so import them after the load. The `applyInstantJson` and `applyXfdf` document operations need document editing in your license. For more import options, refer to the [Instant JSON](https://www.nutrient.io/guides/web/importing-exporting/instant-json.md) and [XFDF](https://www.nutrient.io/guides/web/importing-exporting/xfdf-support.md) guides.

## Set the initial view state

Pass `initialViewState` to open the new document at a specific page, zoom, or layout without the jump that [`instance.setViewState()`](https://www.nutrient.io/api/web/classes/NutrientViewer.Instance.html#setviewstate) causes after loading.

Always derive the value from [`instance.viewState`](https://www.nutrient.io/api/web/classes/NutrientViewer.Instance.html#viewstate) right before calling `instance.load()`. The call rejects any change to viewer-level fields like `showToolbar`, `sidebarMode`, or `readOnly`. A fresh `new NutrientViewer.ViewState()` usually fails this check because its defaults differ from the mounted viewer.

Because `instance.viewState` carries the current document’s page, zoom, and rotation, reset any fields you don’t want to keep:

```js
import NutrientViewer from "@nutrient-sdk/viewer";

async function openOnThirdPageWithDefaults(instance) {
  try {
    await instance.load({
      document: "/second.pdf",
      // Page indexes start at 0, so 2 opens the third page.
      initialViewState: instance.viewState
        .set("currentPageIndex", 2)
        .set("zoom", NutrientViewer.ZoomMode.AUTO)
        .set("pagesRotation", 0)
    });
  } catch (error) {
    console.error("Failed to load document:", error.message);
  }
}
```

An out-of-range `currentPageIndex` doesn’t reject; the viewer logs a console warning and falls back to a valid page. A custom zoom outside the new document’s range falls back to `ZoomMode.AUTO` the same way. When you omit `initialViewState`, zoom resets to `ZoomMode.AUTO` even if `NutrientViewer.load()` received a different `initialViewState`.

To change viewer-level fields, call `instance.setViewState()` before or after the switch. For the full list of supported document view fields, refer to [`InstanceLoadConfiguration`](https://www.nutrient.io/api/web/interfaces/InstanceLoadConfiguration.html).

## Load password-protected documents

Pass `password` directly when your app knows it:

```js
async function openProtectedDocument(instance, password) {
  try {
    await instance.load({ document: "/protected.pdf", password });
  } catch (error) {
    console.error("Failed to load protected document:", error.message);
  }
}
```

Unlike `NutrientViewer.load()`, `instance.load()` never shows the built-in password prompt, and `maxPasswordRetries` has no effect. When you omit `password`, the viewer calls your [`onPasswordRequired` callback](https://www.nutrient.io/api/web/interfaces/Configuration.html#onpasswordrequired) once. Show your own dialog there and return the password, or `null` if the user cancels. Make sure the callback always settles, because later `instance.load()` calls wait behind it. If the password is wrong or missing, the promise rejects and the current document stays open, except for documents using OPFS [temporary storage](https://www.nutrient.io/guides/web/open-a-document/temp-storage.md).

## Listen for document switches

Because the instance stays the same, use `document.willSwap` and `document.swap` to react when a document changes:

- `document.willSwap` — Fires once the new document opens and the previous one closes, before the new document’s pages and annotations load. Reset `viewState.*` events (page 0, `ZoomMode.AUTO`) fire just before it, and the viewer stays non-interactive until `document.swap`. Use it to clear outgoing UI state, and don’t call document data APIs here.

- `document.swap` — Fires once the new document is ready, right before the `instance.load()` promise resolves. Use it to read new document data and add custom overlay items with [`instance.setCustomOverlayItem()`](https://www.nutrient.io/api/web/classes/NutrientViewer.Instance.html#setcustomoverlayitem).

Both listeners receive a [`DocumentSwapEvent`](https://www.nutrient.io/api/web/interfaces/Events.DocumentSwapEvent.html) with `previousDocument` and `currentDocument`. Register them once, because they stay active across switches:

```js
function watchDocumentSwitches(instance) {
  instance.addEventListener("document.willSwap", ({ previousDocument }) => {
    // Discard UI that belongs to the previous document here.
    // Document data still describes the previous document at this point.
    if (previousDocument.backend === "standalone") {
      console.log("Leaving document:", previousDocument.document);
    }
  });

  instance.addEventListener("document.swap", ({ currentDocument }) => {
    // The new document is ready, so the document API is safe to call.
    if (currentDocument.backend === "standalone") {
      console.log("Now showing document:", currentDocument.document);
    }

    console.log("Page count:", instance.totalPageCount);
  });
}
```

Neither event fires for the first document from `NutrientViewer.load()` or when a switch fails before opening the new document.

## Switch documents in React

In React, create the viewer in one effect and switch documents in a second effect. Keeping the first effect’s dependency array empty keeps the viewer mounted while `documentUrl` changes:

```jsx
import { useEffect, useRef, useState } from "react";
import NutrientViewer from "@nutrient-sdk/viewer";

export default function DocumentViewer({ documentUrl }) {
  const containerRef = useRef(null);
  // The URL that the viewer was last asked to show.
  const requestedUrlRef = useRef(documentUrl);
  const [instance, setInstance] = useState(null);

  // Create the viewer once. It stays mounted while the document changes.
  useEffect(() => {
    const container = containerRef.current;
    if (!container) return;

    let cancelled = false;

    const createViewer = async () => {
      try {
        const loadedInstance = await NutrientViewer.load({
          container,
          document: requestedUrlRef.current,
          useCDN: true
        });

        if (!cancelled) setInstance(loadedInstance);
      } catch (error) {
        if (!cancelled) console.error("Failed to load viewer:", error);
      }
    };

    createViewer();

    return () => {
      cancelled = true;
      NutrientViewer.unload(container);
    };
  }, []);

  // Load later documents into the same viewer.
  useEffect(() => {
    if (!instance || requestedUrlRef.current === documentUrl) return;

    requestedUrlRef.current = documentUrl;

    const switchDocument = async () => {
      try {
        await instance.load({ document: documentUrl });
      } catch (error) {
        // A newer document replaced this one, or the component unmounted.
        if (NutrientViewer.isDocumentLoadSupersededError(error)) return;
        if (error.name === "AbortError") return;

        console.error(`Failed to load ${documentUrl}:`, error);
      }
    };

    switchDocument();
  }, [instance, documentUrl]);

  return <div ref={containerRef} style={{ height: "100vh" }} />;
}
```

The second effect handles quick prop changes through `instance.load()`’s built-in queue and ignores superseded and unmount `AbortError` rejections. In development, React `StrictMode` runs the mount cleanup between double-invocations, so only one viewer stays mounted.

## Limitations

- Works in standalone mode only. Calls reject in server-backed mode and on viewers created with a DWS Viewer API `session`.

- Accepts only `document`, `password`, and `initialViewState`. Other [`Configuration`](https://www.nutrient.io/api/web/interfaces/Configuration.html) keys (including `toolbarItems`, `locale`, `theme`, `instantJSON`, and `XFDF`) reject with an error naming the instance method or reason.

- Downloads URL documents in full without [linearized loading](https://www.nutrient.io/guides/web/performance/linearized-downloads.md).

- Document API calls already running during a switch have undefined results. Await calls like `instance.exportPDF()` before calling `instance.load()`.

- Cancels any running print job when switching. In-progress signing, redaction, document operations, Content Editor saves, and document reloads get up to 60 seconds to finish. After 60 seconds, `instance.load()` rejects and leaves the current document open. Call it again once the operation finishes.

When `instance.load()` doesn’t fit your workflow, reload the viewer instead. For the tradeoffs, refer to the [switch the document or reload the viewer](#switch-the-document-or-reload-the-viewer) section.

## Related guides

- [Embed Web SDK in a dashboard/app shell](https://www.nutrient.io/guides/web/viewer/embed-in-dashboard-app-shell.md)

- [Temporary storage for PDF downloads](https://www.nutrient.io/guides/web/open-a-document/temp-storage.md)

- [Open password-protected PDFs in JavaScript](https://www.nutrient.io/guides/web/features/password-protected-pdfs.md)

- [Subscribe or unsubscribe to API events](https://www.nutrient.io/guides/web/customizing-the-interface/observing-changes-with-events.md)
---

## Related pages

- [Opening specific pages in PDFs using JavaScript](/guides/web/features/open-parameters.md)
- [Open and display PDFs in the browser using JavaScript](/guides/web/open-a-document.md)
- [Open and display PDFs seamlessly in Angular](/guides/web/open-a-document/angular.md)
- [Effortlessly open PDFs in your ASP.NET app](/guides/web/open-a-document/aspnet.md)
- [Effortlessly open and edit PDFs in your browser](/guides/web/open-a-document/blazor.md)
- [Choose the right document opening and loading setup](/guides/web/open-a-document/choose-the-right-document-opening-and-loading-setup.md)
- [Easily open and display PDFs in your browser](/guides/web/open-a-document/electron.md)
- [Open PDFs from an ArrayBuffer using JavaScript](/guides/web/open-a-document/from-arraybuffer.md)
- [Open PDFs from Base64 in the browser using JavaScript](/guides/web/open-a-document/from-base64-data.md)
- [Open and display PDFs from a Blob using JavaScript](/guides/web/open-a-document/from-blob.md)
- [Open documents from Document Engine](/guides/web/open-a-document/from-document-engine.md)
- [Open PDFs using DWS Viewer API](/guides/web/open-a-document/from-dws-viewer-api.md)
- [Open local PDF files using JavaScript](/guides/web/open-a-document/from-local-storage.md)
- [Open and display PDF files from a remote URL using JavaScript](/guides/web/open-a-document/from-remote-url.md)
- [Effortlessly open and display PDFs in the browser](/guides/web/open-a-document/html5.md)
- [Open image files from an array buffer using JavaScript](/guides/web/open-a-document/image-from-arraybuffer.md)
- [Open Base64 image files using JavaScript](/guides/web/open-a-document/image-from-base64-data.md)
- [Open image files from a Blob using JavaScript](/guides/web/open-a-document/image-from-blob.md)
- [Open local image files using JavaScript](/guides/web/open-a-document/image-from-local-storage.md)
- [Open image files from a URL using JavaScript](/guides/web/open-a-document/image-from-remote-url.md)
- [Open PDFs using jQuery and JavaScript](/guides/web/open-a-document/jquery.md)
- [Effortlessly open and display PDFs in Laravel](/guides/web/open-a-document/laravel.md)
- [Open and display PDFs in your Next.js app](/guides/web/open-a-document/nextjs.md)
- [Open and display PDFs seamlessly in Nuxt.js](/guides/web/open-a-document/nuxtjs.md)
- [Open MS Office files from an ArrayBuffer using JavaScript](/guides/web/open-a-document/office-from-arraybuffer.md)
- [Open Base64 MS Office files using JavaScript](/guides/web/open-a-document/office-from-base64-data.md)
- [Open MS Office files from a Blob using JavaScript](/guides/web/open-a-document/office-from-blob.md)
- [Open local MS Office files using JavaScript](/guides/web/open-a-document/office-from-local-storage.md)
- [Open MS Office files from a URL using JavaScript](/guides/web/open-a-document/office-from-remote-url.md)
- [Open and display PDFs with PHP](/guides/web/open-a-document/php.md)
- [Open PDFs in Rails applications](/guides/web/open-a-document/rails.md)
- [Open PDFs in React applications](/guides/web/open-a-document/react.md)
- [How to open and display PDFs in your web app](/guides/web/open-a-document/svelte.md)
- [Temporary storage for PDF downloads](/guides/web/open-a-document/temp-storage.md)
- [Open PDFs in the browser with TypeScript](/guides/web/open-a-document/typescript.md)
- [Open PDFs in Vue.js applications](/guides/web/open-a-document/vuejs.md)

