Switch documents without reloading the viewer
instance.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 and later, in standalone mode only. It isn’t available in server-backed mode or with DWS Viewer API. For details, refer to the limitations section.
Load another document
Call instance.load() on the instance that NutrientViewer.load() returned:
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 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 section. |
initialViewState | Optional. Initial page, zoom, or layout for the new document. Refer to the set the initial view state section. |
Keep these rules in mind for document:
- URL loads reuse the
httpHeadersfromNutrientViewer.load(). Fetch the file in your app and pass anArrayBufferwhen the next document needs different headers. - An
ArrayBuffertransfers ownership to the viewer, even when the load fails. Copy it first withbuffer.slice(0)if you want to retry. Blobinputs aren’t accepted. Convert them withawait blob.arrayBuffer()first.
For the full type and key rules, refer to InstanceLoadConfiguration 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() 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 | 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 to restore each tab’s page and zoom, and export unsaved changes 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 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() so fast clicks don’t produce unhandled promise rejections:
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() 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. That is the default (
"auto") for larger URL-loaded PDFs and closes the previous document first. SettempStorageto"memory"onNutrientViewer.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:
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:
AutoSaveMode.IMMEDIATE(the standalone default) andAutoSaveMode.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() and export with instance.exportPDF() or instance.exportInstantJSON() before calling instance.load():
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 and XFDF 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() causes after loading.
Always derive the value from instance.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:
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.
Load password-protected documents
Pass password directly when your app knows it:
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 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.
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. ResetviewState.*events (page 0,ZoomMode.AUTO) fire just before it, and the viewer stays non-interactive untildocument.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 theinstance.load()promise resolves. Use it to read new document data and add custom overlay items withinstance.setCustomOverlayItem().
Both listeners receive a DocumentSwapEvent with previousDocument and currentDocument. Register them once, because they stay active across switches:
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:
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, andinitialViewState. OtherConfigurationkeys (includingtoolbarItems,locale,theme,instantJSON, andXFDF) reject with an error naming the instance method or reason. - Downloads URL documents in full without linearized loading.
- Document API calls already running during a switch have undefined results. Await calls like
instance.exportPDF()before callinginstance.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 section.
Related guides
- Embed Web SDK in a dashboard/app shell
- Temporary storage for PDF downloads
- Open password-protected PDFs in JavaScript
- Subscribe or unsubscribe to API events