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.
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.
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
});