Note: This release is in preview. Features described here don’t become generally available until the latest general availability date that Salesforce announces for this release. Before then, and where features are noted as beta, pilot, or developer preview, we can’t guarantee general availability within any particular time frame or at all. Make your purchase decisions only on the basis of generally available products and features.
Use Third-Party JavaScript in an LWC Offline-Enabled Component
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.
- 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});