How do you integrate third-party JavaScript libraries into LWC using platformResourceLoader?
Answer
Basics: Third-party code (Chart.js, D3, moment, custom CSS) cannot just be <script>-tagged in LWC. You upload it as a static resource, import its URL with @salesforce/resourceUrl/name, and load it from JavaScript.
How it works: Import loadScript, loadStyle and the resource. Call them with this and the full URL (for a zip resource, append the file path). They return Promises; usually run them from renderedCallback with a guard flag so they run once, then initialize the library (for a chart, onto a canvas obtained from this.template.querySelector). Use lwc:dom="manual" on a container when the library injects its own DOM.
Advanced / deep dive: A script is loaded once per page per URL, so repeated component instances reuse it. Libraries must work under the security layer: Locker blocked many; Lightning Web Security is far more compatible, but test each library. Content Security Policy blocks arbitrary external CDNs, so use static resources (or CSP Trusted Sites where allowed). Static resources are limited (about 5 MB each and 250 MB per org; verify in current release notes), so use minified builds and zip files. Cache-busting follows resource versioning, and public caching of static resources applies. Use Promise.all([loadScript(...), loadStyle(...)]) to parallelize. In Jest, the module is stubbed to resolve immediately, but global library objects must be mocked. For heavy libraries, load lazily only when the feature is shown. Prefer native base components or SVG where possible.
Code / config example:
import { LightningElement } ;
{ loadScript, loadStyle } ;
;
{
loaded = ;
chart;
() {
(.) ;
. = ;
{
.([(, + )]);
ctx = ..().();
. = .(ctx, { : , : { : [], : [{ : [] }] } });
} (e) {
.(, e);
}
}
}