Loading Third-Party JavaScript Libraries
By the end of this lesson, you'll be able to:
- Upload a third-party JavaScript library as a static resource
- Load a script or stylesheet at runtime using platformResourceLoader
- Guard against loading the same resource more than once
Prerequisites: "Custom Labels and Custom Permissions"
Static Resources
A third-party JavaScript library (e.g. a charting library) is uploaded to Salesforce as a Static Resource — a file stored in the org and referenced by a developer-chosen name, the same mechanism used for images or other static assets.
loadScript and loadStyle
import { LightningElement } from 'lwc';
import { loadScript } from 'lightning/platformResourceLoader';
import CHART_JS from '@salesforce/resourceUrl/chartjs';
export default class SalesChart extends LightningElement {
chartJsLoaded = false;
async renderedCallback() {
if (this.chartJsLoaded) {
return;
}
this.chartJsLoaded = true;
try {
await loadScript(this, CHART_JS);
this.initializeChart();
} catch (error) {
this.error = error;
}
}
}
loadScript/loadStyle (imported from lightning/platformResourceLoader) are Promise-based (Module 4) functions that load a static resource at runtime. The chartJsLoaded guard flag is essential — without it, renderedCallback firing multiple times (Module 3) would attempt to load the same script repeatedly.
Why This Matters in Real Projects
Plenty of genuinely useful JavaScript functionality — charting, PDF generation, rich text editing — comes from third-party libraries never built for Salesforce specifically. This is the standard, supported bridge for bringing that functionality into a component.
Exercise
Write the import statements needed to load a static resource named "momentjs" using loadScript.
Show hint
Two imports are needed: the loader function and the resource URL.
Exercise
Challenge: explain, as a comment, why a guard flag like chartJsLoaded is necessary before calling loadScript inside renderedCallback.
Show hint
Recall how many times renderedCallback can fire.
Loading Third-Party JavaScript Libraries Quiz
My Notes
Log in to keep private notes on this lesson.
Questions about this lesson
No questions yet — be the first to ask.
Log in to ask a question about this lesson.
Summary
A static resource plus loadScript/loadStyle is how LWC brings in external JavaScript libraries that aren't part of the LWC/SLDS ecosystem — a Promise-based, guarded pattern to avoid loading the same library twice.