Use Third-Party JavaScript in an LWC Offline-Enabled Component

Use static resources to provide access to third-party JavaScript libraries in your Lightning web components. To enable JavaScript libraries in static resources to be used while offline, follow these guidelines.

Loading JavaScript libraries stored in a static resource is straightforward, and fully documented. We present only a simple example here. See Use Third-Party JavaScript Libraries the Lightning Web Component Developer Guide for complete details.

LWC Offline doesn’t support archive static resources at this time. This limitation poses a challenge for libraries that consist of many separate JavaScript files. While you can create a separate static resource for each file and load them individually, that’s tedious. Look for a merged, concatenated, or minimized version of your JavaScript library; transformed versions of libraries are often provided by the developer for performance and ease of deployment.

Important

The critical elements of an offline-ready implementation are:
  • Access the URL of the resource by importing it using the @salesforce/resourceUrl module.
  • Load the library using the loadScript() function of the platformResourceLoader module, and then;
  • Call your library’s entry point, initialization or factory function, or otherwise start using the library in a then() block chained from your loadScript() call.

While there are other methods for loading JavaScript libraries in an LWC, the preceding elements are required for offline access to function. Static resources aren’t primed in advance; users must load (view) a component using the static resource before going offline. This behavior will change in a future release.

Important

Example

// javascriptFromStaticResource.js
import { LightningElement } from 'lwc';
import { loadScript } from 'lightning/platformResourceLoader';
import myLib from '@salesforce/resourceUrl/myLib';

export default class JavascriptFromStaticResource extends LightningElement {
    loadScript(this, myLib)
    .then(() => {
        let result = myLib.myFunction(2,2);
    });
}

If you must load multiple separate JavaScript files, wrap them in a Promise, and call the initialization function after all of your calls to loadScript() have resolved. For example:

Promise.all([
    loadScript(this, resourceName1),
    loadScript(this, resourceName2),
    loadScript(this, resourceName3)
]).then(() => { 
    // Start using the library here
});