# Best Practice

Foxit PDF SDK for Web runs in a browser sandbox in a network environment. Choosing a correct website operation scheme and Foxit PDF SDK for Web configuration can make Foxit PDF SDK for Web run faster. The following section give references on website operation optimization and Foxit PDF SDK for Web configuration.

# Website assets optimization

# Gzip and Brotli compression

Compression is a way to shrink the assets size and reduce the downloading time. The following table shows the compressed size using gzip and brotli on UIExtension.css and UIExtension.full.js.

File Original size Gzip Brotli
UIExtension.css 1.2M 213kb 156kb
UIExtension.full.js 2.6M 534kb 443kb

NOTE: Although the brotli compression algorithm provided by Google is superior to gzip in compression ratio. But brotli is not natively supported by all browsers, such as Microsoft's IE. Decompression of brotli in IE requires the use of a JavaScript engine. This time-consuming process offsets the advantages of Brotli and consumes website loading performance.

NOTE (Brotli and HTTPS):

Content-Encoding: br means “this response body is Brotli-compressed; the browser should decompress it automatically.”
Chrome, Edge, Firefox, and Safari typically advertise br in Accept-Encoding only on HTTPS pages (and, in Chrome, on localhost). On plain HTTP to a LAN IP (for example http://192.168.1.100:8080), they usually do not advertise br.

Servers should therefore negotiate compression from Accept-Encoding: use Brotli when the client advertises br, otherwise fall back to gzip or uncompressed. Never force Content-Encoding: br when the client did not advertise br, or the browser may fail with ERR_CONTENT_DECODING_FAILED. See Transfer compression for JR wasm modules for the full guide.

# Cache

Caching resource files can avoid downloading the same assets again and again. The /lib library in the SDK and the font files in /external are recommended for front-end caching. To learn more, check out Google (opens new window) and Mozilla (opens new window) for HTTP cache.

# Foxit PDF SDK for Web configuration

# Read only

If the following scenario is your current needs, it is recommended that you load the Foxit PDF SDK for Web read-only to improve rendering performance.

Applicable scenario:

  • complex PDF documents generated by CAD
  • page rendering speed is high preference
  • no page editing requirements

Code Example:

<script src="path/to/UIExtension.full.js"></script>
<script src="path/to/allInOne.js"></script>
<script>
    var pdfui = new UIExtension.PDFUI({
        ...
        viewerOptions:{
            customs: {
                getDocPermissions: function () {
                    return 0;// 0 means ReadOnly 
                }
            }
        ...
    })
</script>

or

<script src="path/to/PDFViewCtrl.full.js"></script>
<script>
    var pdfviewer = new PDFViewCtrl.PDFViewer({
        ...
        customs: {
                getDocPermissions: function () {
                    return 0;// 0 means ReadOnly 
                }
            }
        ...
    })
</script>

# Transfer compression for JR wasm modules

JR engine modules ship as plain *.wasm files in the SDK package (including gsdk.wasm and on-demand modules such as optimizer.wasm and pageformat.wasm). The SDK requests lib/jr-engine/gsdk/<module>.wasm?h=<md5>. When the file server dynamically returns gzip or br based on Accept-Encoding, the browser decompresses the body and the SDK receives decoded WASM bytes.

Enable dynamic compression on the file server for these assets (negotiate per request; do not ship precompressed sidecars in the SDK package).

# Gzip vs Brotli

Aspect Gzip Brotli
Compression ratio Good Usually better than gzip (smaller payload)
Browser advertisement gzip is commonly advertised on HTTP and HTTPS br is mainly advertised on HTTPS (and Chrome localhost)
When to prefer Safer default for plain HTTP / LAN IP access Prefer on production HTTPS for smaller downloads
Server support Built into Nginx / Apache / IIS widely Requires the matching module (e.g. Nginx ngx_brotli, Apache mod_brotli)

Recommendations:

  1. Use HTTPS in production and enable both Brotli and Gzip (prefer br, fall back to gzip).
  2. When only plain HTTP is available (for example a LAN IP), prefer Gzip. Never force Content-Encoding: br unless the client advertised br.
  3. Always send Vary: Accept-Encoding, and set Content-Type: application/wasm for *.wasm.

# Gzip dynamic compression example (Nginx)

http {
    gzip on;
    gzip_vary on;
    gzip_proxied any;
    gzip_comp_level 5;
    gzip_types application/wasm application/octet-stream;

    server {
        # ...
        location ~* /lib/jr-engine/gsdk/.*\.wasm$ {
            root "path/to/websdk";
            default_type application/wasm;
            # the gzip module negotiates from Accept-Encoding
        }
    }
}

# Brotli dynamic compression example (Nginx)

Requires ngx_brotli (opens new window):

http {
    brotli on;
    brotli_comp_level 5;
    brotli_types application/wasm application/octet-stream;

    # Keep gzip as a fallback when br is not advertised
    gzip on;
    gzip_vary on;
    gzip_types application/wasm application/octet-stream;

    server {
        # ...
        location ~* /lib/jr-engine/gsdk/.*\.wasm$ {
            root "path/to/websdk";
            default_type application/wasm;
            add_header Vary Accept-Encoding always;
        }
    }
}

# Apache (httpd)

Gzip (mod_deflate):

<Directory "/path/to/websdk/lib/jr-engine/gsdk">
    <IfModule mod_deflate.c>
        AddOutputFilterByType DEFLATE application/wasm application/octet-stream
    </IfModule>
    <FilesMatch "\.wasm$">
        Header set Content-Type "application/wasm"
        Header append Vary "Accept-Encoding"
    </FilesMatch>
</Directory>

Brotli (mod_brotli, keep deflate enabled as a fallback):

<Directory "/path/to/websdk/lib/jr-engine/gsdk">
    <IfModule mod_brotli.c>
        AddOutputFilterByType BROTLI_COMPRESS application/wasm application/octet-stream
    </IfModule>
    <IfModule mod_deflate.c>
        AddOutputFilterByType DEFLATE application/wasm application/octet-stream
    </IfModule>
    <FilesMatch "\.wasm$">
        Header set Content-Type "application/wasm"
        Header append Vary "Accept-Encoding"
    </FilesMatch>
</Directory>

# IIS

Enable dynamic compression at the site or under lib/jr-engine/gsdk/, and map the .wasm MIME type:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <system.webServer>
    <staticContent>
      <mimeMap fileExtension=".wasm" mimeType="application/wasm" />
    </staticContent>
    <urlCompression doStaticCompression="true" doDynamicCompression="true" />
    <httpProtocol>
      <customHeaders>
        <add name="Vary" value="Accept-Encoding" />
      </customHeaders>
    </httpProtocol>
  </system.webServer>
</configuration>

Brotli on IIS requires an additional compression provider. Built-in gzip/deflate negotiation usually works on both HTTP and HTTPS.

# CDN / object storage

Upload plain *.wasm and let the CDN apply dynamic compression from the client Accept-Encoding (or enable the CDN’s gzip/brotli feature). Suggested response headers:

Header Value
Content-Type application/wasm
Vary Accept-Encoding
Cache-Control e.g. public, max-age=31536000, immutable (safe because URLs include ?h=<md5>)

# Caching wasm modules

Use one or more of the following (they can be combined):

  1. HTTP cache (recommended baseline)
    SDK requests include ?h=<content-md5>. When the engine is upgraded, the hash changes and browsers fetch the new URL. Configure long-lived cache headers on *.wasm. Cache the full URL including the query string.

  2. Built-in Cache API (cache-first)
    In environments that support the Cache API (opens new window), WasmLoader cache-firsts *.wasm by the full request URL (including ?h=<md5>). A cache hit is served from Cache Storage; a miss fetches the network and stores the result. Hash changes naturally bust the old entry. No Service Worker registration is required.

# Transfer compression for JR fonts

The SDK bundles third-party fonts with .brotli files under external/brotli (for example NotoSans-Regular.ttf.brotli). To reduce download time and avoid slow decompression on the client, the server can deliver the fonts in either of these ways:

  1. Deliver the .brotli file with Content-Encoding: br so the browser decodes the transfer encoding natively. Deploy the bundled *.brotli files unchanged and let the server negotiate br from the client's Accept-Encoding (prefer br, fall back to gzip or uncompressed; never force Content-Encoding: br unless the client advertised it).
  2. Deliver a plain uncompressed font file (.ttf / .otf / .woff / .woff2 / .ttc). Set a font MIME type (for example font/ttf or application/font-sfnt) and configure the SDK's fontPath to point to the directory holding these files.

The SDK automatically detects whether the received bytes already form a complete font and uses them directly; it decompresses in‑browser only when the server actually sends compressed font bytes. Both options also work over plain HTTP.

Note: Browsers advertise br mainly on HTTPS (and under Chrome localhost). For plain HTTP / LAN deployments, prefer serving uncompressed fonts (option 2 above). See Gzip and Brotli compression for general negotiation guidance.

# Preload webassembly artifacts

Starting from version 7.1.1, Foxit PDF SDK for Web provides a script file called "preload-jr-worker.js" to load webWorker scripts and wasm/asm in advance, this can greatly save document rendering time.

Code Example:

<body>
    <div id="pdf-ui"></div>
    <script>
        var licenseSN = "Your license SN";
        var licenseKey = "Your license Key";
    </script>

    <!-- Add the preload-jr-worker.js-->
    <script src="./lib/preload-jr-worker.js"></script>
    <script>
        var readyWorker = preloadJrWorker({
            workerPath: './lib/',
            enginePath: './lib/jr-engine/gsdk',
            fontPath: './external/brotli',
            licenseSN: licenseSN,
            licenseKey: licenseKey
        })
    </script>

    <script src="./lib/UIExtension.full.js"></script>
    <script>

        var pdfui = new UIExtension.PDFUI({
            viewerOptions: {
                libPath: './lib', // the library path of web sdk.
                jr: {
                    readyWorker: readyWorker,
                }
            },
            renderTo: '#pdf-ui', // the div (id="pdf-ui").
            appearance: UIExtension.appearances.adaptive,
            addons: [
                '```'
            ]
        });
        ...

# Tiling size

Note: Starting from version 8.5, the Web SDK no longer uses the tileSize rendering mode. The following content is only applicable to the versions prior to 8.5.

Foxit PDF SDK for Web performs raster scan when rendering the page. If the currently rendered page layout is too large, the rendering speed of the page will be extremely slow. It is recommended that you enable tileSize rendering mode when opening this large page layout. Currently, the supported tileSize range is 500-3000px. In our internal comprehensive test, the rendering speed is optimal with the tileSize being set as 1200px. But it may vary with your document complex. You can set different tileSize such as 200, 3600, and etc. in your test environment according to the needs of the actual scenario to obtain the most suitable configuration scheme.

Applicable scenario:

  • Complex documents with large page layout

Code Example:

<script src="path/to/UIExtension.full.js"></script>
<script src="path/to/allInOne.js"></script>
<script>
    var pdfui = new UIExtension.PDFUI({
        ...
        viewerOptions:{
            tileSize:1200,
            ...
        }
        ...
    })
</script>

or

<script src="path/to/PDFViewCtrl.full.js"></script>
<script>
    var pdfviewer = new PDFViewCtrl.PDFViewer({
        ...
        tileSize:1200,
        ...
    })
</script>

# Zoom

Foxit PDF SDK for Web opens PDF with fitWidth by default for desktop, and with actual scale by default for mobile. For mobile, if you display the pages in fitWidth mode, showing or hiding the left toolbar will cause the PDF pages to be re-rendered as the viewport size changes, which will affect the performance. To circumvent this problem, it is recommended to display the pages in actual scale.

# Rendering mode

Starting in version 8.5, the option annotRenderingMode has been deprecated. By default, Foxit PDF SDK for Web uses the native mode (using WebAssembly as the rendering engine) to render annotations and form controls. The native render has been significantly optimized to ensure the rendering quality and speed, so the canvas rendering is no longer required.

# Document loading

# Synchronous loading

Synchronous loading is to first obtain the complete binary stream of the file for loading, which is a compromised way of memory and performance. For documents between 50M and 500M, this method is recommended.

Code Example:

<script src="path/to/UIExtension.full.js"></script>
<script src="path/to/allInOne.js"></script>
<script>
    var pdfui = new UIExtension.PDFUI({...})
    var blob = getBlob();
    pdfui.openPDFByFile(blob)
</script>

# Asynchronous loading

Asynchronous loading does not require a complete file stream, only the required part is obtained during loading. When the file is too large (greater than 500MB) and cannot be put in memory at all, or when you only need to request part of the document at a time, it is recommended to load the document in this way to get a good performance experience.

Code Example:

<script src="path/to/UIExtension.full.js"></script>
<script>
    var pdfui = new UIExtension.PDFUI({...})
    pdfui.openPDFByHttpRangeRequest({
        range:{
            url:'../../../docs/FoxitPDFSDKforWeb_DemoGuide.pdf',
        }
    })
</script>

# Loading document from memory arrayBuffer

Loading from arrayBuffer is to store the entire file stream to and load from in wasm/asm memory. For small local documents (less than 500MB) , or when the entire document stream can be obtained in a short time, it is recommended to load in this way. This method has the advantages of high reading efficiency and fast loading speed. To enable this method, pass in the callback function getLoadingMode() at the time of constructing the PDFUI. When it returns 1, it means that it is loaded from memory arrayBuffer.

Code Example:

<script src="path/to/UIExtension.full.js"></script>
<script>
    var pdfui = new UIExtension.PDFUI({
        ...
        customs:{
            getLoadingMode:function(file){return 1}
        }
        ...
    })
</script>

If you have implemented your own file open control, you can use the following method to load:

var pdfui = new UIExtension.PDFUI({...})
...//event bind context
{
    var arrayBuffer=getArrayBuffer();
    pdfui.openPDFByFile(arrayBuffer);
}
...