Sub topic 9
Using third-party libraries from static resources
This chapter covers how to load a JavaScript library from a static resource, what Lightning Web Security (LWS) does to that library, and how to diagnose a library that stops working. It assumes you can build a basic Lightning web component, use async/await, and upload a static resource. It also assumes you have read the earlier chapters on namespace sandboxes, distortions, and DOM access.
Where a library runs under LWS
A library from a static resource is not a separate trusted program. When your component calls loadScript, the platform fetches the file and evaluates it inside the JavaScript sandbox for your component's namespace. The library then runs with the same distorted window, document, and built-in objects that your own code sees. This has four consequences:
- The library can do what your component can do, and nothing more. If a distortion blocks an API, the library fails when it calls that API.
- Globals the library creates, such as
window.Chart, live in your namespace's sandbox. Other namespaces cannot see them. - Two namespaces that each load the same library get two independent copies.
- A library's DOM queries are filtered the same way yours are, so it cannot find elements that belong to another namespace.
Loading a library step by step
Upload the library as a static resource, for example one named chartjs. Then use loadScript from lightning/platformResourceLoader. The first argument must be this, so the platform knows which component and namespace the script belongs to.
<template>
<lightning-card title="Chart">
<div class="slds-p-around_medium">
<canvas class="chart-canvas"></canvas>
</div>
</lightning-card>
</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;
chart;
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);
}
}
disconnectedCallback() {
if (this.chart) {
this.chart.destroy();
}
}
}Four details in this example matter:
- The guard flag.
renderedCallbackruns after every render. SettinglibraryLoadedbefore theawaitstops a second render from starting a second load. - The try/catch. A rejected
loadScriptpromise, or a distortion error thrown by the library, is easy to miss without it. - The element reference. The component passes the canvas it found through
this.template.querySelector. The library never searches the document for it. - The cleanup.
disconnectedCallbackdestroys the chart so the library releases its listeners and timers.
Zip resources and file paths
If the static resource is a zip archive, the resource URL points to the archive root. Append the path of the file inside it:
import D3 from '@salesforce/resourceUrl/d3';
await loadScript(this, D3 + '/d3.min.js');Use the same pattern with loadStyle for CSS files. A wrong path gives a rejected promise, usually with a 404 in the network tab.
Loading several files in the right order
Promise.all starts the loads in parallel, so the scripts can finish in any order. If one script depends on another, load them one after the other:
import { loadScript, loadStyle } from 'lightning/platformResourceLoader';
import LIBS from '@salesforce/resourceUrl/mapLibs';
async function loadMapLibs(component) {
await loadScript(component, LIBS + '/core.js');
await loadScript(component, LIBS + '/plugin.js'); // needs core.js first
await loadStyle(component, LIBS + '/map.css');
}Independent files, such as a script and its stylesheet, can go in Promise.all.
Letting a library draw into the DOM
Some libraries build their own DOM. D3, for example, appends SVG elements. Elements added by code outside the LWC template are not tracked by the component's synthetic shadow. To make this work, put the lwc:dom="manual" directive on the container the library writes into, and hand the library that container as an element:
<template>
<div class="host" lwc:dom="manual"></div>
</template>import { LightningElement } from 'lwc';
import { loadScript } from 'lightning/platformResourceLoader';
import D3 from '@salesforce/resourceUrl/d3';
export default class D3Host extends LightningElement {
initialized = false;
async renderedCallback() {
if (this.initialized) {
return;
}
this.initialized = true;
try {
await loadScript(this, D3 + '/d3.min.js');
const container = this.template.querySelector('.host');
const svg = window.d3
.select(container)
.append('svg')
.attr('width', 120)
.attr('height', 40);
svg.append('circle').attr('cx', 20).attr('cy', 20).attr('r', 15);
} catch (error) {
console.error('D3 failed to load or render', error);
}
}
}Passing the element avoids calls such as d3.select('body') or d3.select('#chart'). Those go through the global document, and a distorted document may not return what the library expects. Passing an element you found in your own template works the same way under every security mode.
Rules for choosing and preparing a library
- Use a build meant for a plain script tag.
loadScriptevaluates a classic script. Use the UMD or IIFE build, usually named likelibrary.umd.jsorlibrary.min.js. A pure ES module build will fail with a syntax error onimportorexport. - Pin the version in the resource name or metadata. Static resources are cached, and upgrading a library can change which APIs it calls. Review the new version before you replace the resource.
- Pass elements in, not selectors. Give the library the canvas or container you already hold.
- Do not rely on cross-namespace globals. A library loaded by a managed package component is not visible to your component, and the reverse is also true.
- Avoid libraries that patch built-ins or the whole document. They are the most likely to meet a distortion. Examples are libraries that attach listeners to
documentfor the entire page, or ones that measure or change elements outside their own container. - Check for dynamic code. Libraries that call
evalornew Functionmay be blocked by the Content Security Policy of the page, not by LWS itself. The next chapters cover CSP in more detail. - Test each library in the actual org with LWS on. A sandbox or scratch org with the setting enabled is enough. Library behavior is the most org-specific part of a migration.
What works and what tends to break
| Library behavior | Usual result under LWS | What to do |
|---|---|---|
| Draws into an element you pass in | Works | Pass `this.template.querySelector(...)` results |
| Reads or sets its own `window.Library` global | Works within your namespace | Read it as `window.Library` after `loadScript` resolves |
| Looks up elements with `document.querySelector` | May return null | Pass elements instead of selectors |
| Appends nodes to `document.body` | May be blocked or invisible to your template | Render into a container with `lwc:dom="manual"` |
| Needs a global shared with another namespace | Undefined global | Pass data using `@api` and events, as in the previous chapter |
| Uses `eval` or `new Function` | May fail under CSP | Use a build without dynamic evaluation |
| Ships as an ES module | Syntax error | Use the UMD or IIFE build |
| Needs a feature a distortion blocks | Error or no-op | Replace the library or change the code |
Diagnosing a failing library
Work through these checks in order. They separate a load problem from a sandbox problem from a library bug.
- Does
loadScriptreject? If yes, the problem is the URL, the zip path, or a script that failed to evaluate. Open the browser's network tab and check the request. - Is the global defined after load? Log
typeof window.Library. If it isundefined, the script ran but exported itself some other way, usually as a module or CommonJSexports. - Does the first library call fail? Read the error message and the stack. A
TypeErroronnulloften means a selector returned nothing. An error that mentions a blocked property or method points to a distortion. - Does the same call work with LWS off? In a test org, compare the behavior. If it works only with LWS off, the library depends on something LWS restricts.
- Does the failure appear only in some locations? If it works in your own page but fails in a managed package or in Experience Cloud, check whether the code runs in a different namespace and whether CSP differs there.
After you know the cause, decide between two fixes:
- Change your code when the problem is how you call the library. Examples are passing elements, loading files in order, or using
lwc:dom="manual". - Change the library when the library itself calls blocked APIs, uses dynamic code, or needs globals from another namespace. Choose a different library or an older or newer build before you try to work around the sandbox.
Summary
loadScriptevaluates the library inside your namespace's sandbox, so the library is subject to the same distortions as your code.- Load a UMD or IIFE build, wait for the promise, guard against repeated loads, and wrap the call in try/catch.
- Give libraries elements from
this.templateinstead of letting them search the document, and uselwc:dom="manual"for containers a library fills. - Treat each namespace as having its own copy of a library, and share data through public properties and events.
- When a library fails, check load, then global, then first call, then compare with LWS off, and decide whether to change your code or the library.
Exercise
A component loads d3.min.js with loadScript, then runs window.d3.select('#chart').append('svg'). The call throws because select returned an empty selection. Describe two changes that make this robust under LWS.
Show answer
First, give the library an element from the component's own template instead of an id selector. Add a container such as <div class="host" lwc:dom="manual"></div> to the HTML, get it with this.template.querySelector('.host'), and call window.d3.select(container). Second, make sure the load has finished before the call by putting the select code after await loadScript(this, D3 + '/d3.min.js'), inside a try/catch that logs the error. The lwc:dom="manual" directive lets the library add SVG nodes that the template does not manage.
Exercise
Component A in namespace acme loads a library and sets window.Formatter. Component B in namespace beta calls window.Formatter.format(value) and gets undefined is not an object. Why does this happen, and what should B do?
Show answer
Each namespace has its own sandbox with its own window. The global that acme's library created exists only in the acme sandbox, so beta sees no Formatter. B can load its own copy of the library with loadScript and use that copy, or A can expose the formatted result through a public @api property or method or a custom event, so B never needs the global.