Sub topic 9
Using third-party libraries from static resources
This chapter assumes you know basic LWC structure, async/await, and what a static resource is. You also need the idea from earlier chapters that LWS runs code in a sandbox per namespace and applies distortions to some APIs.
Why libraries need care under LWS
Salesforce does not let you add a <script> tag to a component template. You upload the library as a static resource and load it with loadScript from lightning/platformResourceLoader.
Under LWS, the loaded library runs in the same namespace sandbox as the component that loaded it. The library sees the same distorted window, document, and other APIs that your component sees. It does not run in the page's raw global scope.
This has two effects:
- A library that only uses APIs LWS allows works with no changes.
- A library that depends on an API LWS distorts or blocks can fail, sometimes at load time and sometimes later when you call it.
Loading a library
The example below loads Chart.js from a static resource named chartjs. It loads the library once, then draws a chart on a canvas in the component's own template.
import { LightningElement } from 'lwc';
import { loadScript } from 'lightning/platformResourceLoader';
import CHART_JS from '@salesforce/resourceUrl/chartjs';
export default class ChartHost extends LightningElement {
libraryLoaded = false;
async renderedCallback() {
if (this.libraryLoaded) {
return;
}
this.libraryLoaded = true;
try {
await loadScript(this, CHART_JS);
const canvas = this.template.querySelector('canvas');
this.chart = new window.Chart(canvas, {
type: 'bar',
data: { labels: ['A'], datasets: [{ data: [1] }] }
});
} catch (error) {
// Surface sandbox or load failures instead of failing silently.
console.error('Chart library failed to load or initialize', error);
}
}
}Three details matter here:
- The
libraryLoadedflag stopsrenderedCallbackfrom loading the script on every render. this.template.querySelectorreaches the canvas. Under LWS you query inside your own template, not throughdocument.- The
try/catchmakes a failure visible. A library that breaks in the sandbox otherwise tends to fail with an unclear message.
The component needs a canvas element in its template, with lwc:dom="manual" if the library inserts its own child nodes into an element.
Reaching the library through window
Most libraries attach themselves to window, as window.Chart does above. Under LWS, window is the sandbox's version for your namespace. Code in your namespace sees the library. Code in another namespace does not see it, because that namespace has its own sandbox.
If two namespaces both need the library, each one loads it. Do not rely on one namespace's global being visible to another. To share results, pass data through public @api properties and custom events, as covered in the previous chapter.
Choosing a library that works
Before you adopt a library, check these points:
| Check | Why it matters |
|---|---|
| Does it touch `document` outside your template? | Queries and inserts are limited to what your component owns. |
| Does it use `eval` or build functions from strings? | Content Security Policy can block this. |
| Does it modify built-in prototypes? | Distortions can prevent or isolate the change. |
| Does it load more scripts or styles from other hosts? | Those hosts must be allowed by CSP, and loads that bypass `loadScript` can fail. |
| Is a minified, self-contained build available? | A single file is easier to upload and test. |
If a library fails, first read the browser console error. Then decide between a code change and a library change. Change your code when the problem is how you call the library, such as using document.querySelector to find a target element. Change the library when its internals need an API the sandbox does not allow. A newer version, or a different library for the same job, is often the fix.
Common mistakes
- Calling
loadScriptinconnectedCallbackand then querying the template. The template has not rendered yet, so the element is missing. - Loading the same resource repeatedly because there is no guard flag.
- Passing
document.bodyor another element outside your template to the library as its container. - Expecting a global created in one namespace to exist in another.
Exercises
Exercise
Your component loads a charting library with loadScript, and it works. A component in a different namespace on the same page tries to use window.Chart and gets undefined. Why, and what is the fix?
Show answer
Each namespace runs in its own sandbox with its own window, and the library was loaded into your namespace's sandbox only. The other namespace should load the library itself, or you should share the result of the work (data or events) through public @api properties and custom events instead of sharing the global.
Exercise
A library works when you call new window.Chart(...) on a canvas inside your template, but fails when you pass it document.querySelector('#chart'). Name the cause and the correction.
Show answer
Under LWS, document queries cannot reliably reach elements owned by your component, and the library cannot use elements outside your template. Use this.template.querySelector('canvas') and pass that element to the library.