Newer Version Available
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
1// javascriptFromStaticResource.js
2import { LightningElement } from 'lwc';
3import { loadScript } from 'lightning/platformResourceLoader';
4import myLib from '@salesforce/resourceUrl/myLib';
5
6export default class JavascriptFromStaticResource extends LightningElement {
7 loadScript(this, myLib)
8 .then(() => {
9 let result = myLib.myFunction(2,2);
10 });
11}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:
1Promise.all([
2 loadScript(this, resourceName1),
3 loadScript(this, resourceName2),
4 loadScript(this, resourceName3)
5]).then(() => {
6 // Start using the library here
7});