Preloading

Preload PDFs, MS Office documents, images and more in a PDF viewer using this JavaScript sample (no servers or other external dependencies required). Preloading documents in a PDF Viewer gives users near instantaneous access to large and complex documents – helping improve their overall user experience in your application. This sample works on all browsers (including IE11) and mobile devices without using plug-ins. Learn more about our Web SDK.

1const viewerElement = document.getElementById('viewer');
2// eslint-disable-next-line no-undef
3const WebViewerConstructor = isWebComponent() ? WebViewer.WebComponent : WebViewer;
4
5WebViewerConstructor(
6 {
7 path: '../../../lib',
8 // in this example we are using 'all' to preload resources for office files
9 // when working with only pdf, set to 'pdf' to avoid downloading unneeded resources
10 preloadWorker: 'all',
11 },
12 viewerElement
13).then(instance => {
14 samplesSetup(instance);
15 const preLoadFiles = ['../../../samples/files/demo.pdf', '../../../samples/files/simple-excel_2007.xlsx', '../../../samples/files/simple-word_2007.docx'];
16
17 const documentsDiv = document.getElementById('documents');
18
19 preLoadFiles.forEach(file => {
20 const div = document.createElement('div');
21 div.innerHTML = file.split('/').slice(-1)[0];
22
23 const button = document.createElement('button');
24 button.innerHTML = 'Loading';
25
26 const list = document.createElement('li');
27 list.appendChild(div);
28 list.appendChild(button);
29
30 documentsDiv.appendChild(list);
31
32 // using this instead of 'fetch' for IE11 support
33 const xhr = new XMLHttpRequest();
34 xhr.open('GET', file, true);
35 xhr.responseType = 'blob';
36 xhr.onload = function() {
37 const doc = this.response;
38 if (this.status === 200) {
39 button.onclick = () => {
40 viewerElement.style.visibility = 'visible';
41 // file name is required for office files, 'loadDocument' will assume files are pdf if there isn't a filename
42 instance.UI.loadDocument(doc, { filename: file.split('/').slice(-1)[0] });
43 };
44 button.innerHTML = 'Open';
45 }
46 };
47 xhr.send();
48 });
49
50 document.getElementById('toggle').addEventListener('click', () => {
51 if (viewerElement.style.visibility === 'hidden') {
52 viewerElement.style.visibility = 'visible';
53 } else {
54 viewerElement.style.visibility = 'hidden';
55 }
56 });
57});

Did you find this helpful?

Trial setup questions?

Ask experts on Discord

Need other help?

Contact Support

Pricing or product questions?

Contact Sales