Please note that I'm very new to SalesForce and LWC (barely a month into it).
If I look at the LWC Recipes where they demo D3.js and Chart.js, how can you make them load once globally? The goal is to use this external library in multiple pages of SalesForce, so how could we load the external library only once and not every time we visit a new page. Basically, I got an LWC Component working, it does load the external lib and everything is fine BUT I'm trying to avoid reloading this lib every single time (this external lib I have also requires jQuery which I have to reload every time), there about 5 loadScripts
and some CSS with loadStyles
, I'd be happy to have to do this only in 1 place.
I saw this SO answer which summarize how to deal with external library import but again it's only showing how to use it once but not really in a SPA fashion (single page app).
An example of Chart.js loaded as an external script, with this GitHub LWC Recipe
import { LightningElement } from 'lwc';
import { loadScript } from 'lightning/platformResourceLoader';
import chartjs from '@salesforce/resourceUrl/chart';
export default class LibsChartjs extends LightningElement {
error;
chart;
chartjsInitialized = false;
renderedCallback() {
if (this.chartjsInitialized) {
return;
}
this.chartjsInitialized = true;
loadScript(this, chartjs)
.then(() => {
const canvas = document.createElement('canvas');
this.template.querySelector('div.chart').appendChild(canvas);
const ctx = canvas.getContext('2d');
this.chart = new window.Chart(ctx, this.config);
})
.catch(error => {
this.error = error;
});
}
}
You might suggest to create an LWC Component and then use it as a Child Component, however in our use case we have issue with the external lib that we are trying to use and I had another SO Question. So I'm basically trying to avoid having issues with Child/Parent readonly object properties because that external lib uses pointer to update certain object properties.
I'm assuming that there must be a way to load the external lib into the window
DOM object that can remain in this object and be available from any new LWC.