If you are planning to use a third-party JavaScript library in Lightning Web Components, there is a behavior you have to be aware of: you get an undefined error when you try to load a JavaScript library that has already been loaded by another component.
This can happen for example in a Salesforce community that includes two or more Lightning Web Components using the same external library.
Itโs important to note that this behaviour is different to the one in Aura components. In Aura, you can specify the same JavaScript library multiple times without any problem. Please note though, that an undefined error can also happen in a Lightning Web Component that tries to load a library that an Aura component previously loaded.
In my case the JavaScript library that was generating this error was Highcharts.
The following code generates an undefined error if highcharts713.js has already been loaded:
loadScript(this, Highcharts_ZIP + '/highcharts713.js')
.then(() => {
this.createChart();
})
.catch(error => {
// Here error was undefined !
let message = "Unknown error loading Highcharts";
if (error) {
message = error.message;
}
this.dispatchEvent(
new ShowToastEvent({
title: 'Error loading Highcharts',
message: message,
variant: 'error',
}),
);
})
The solution to this problem (thanks to my colleague Tom for his help in solving this problem) is to check if Highcharts is already available before trying to load it:
if (typeof Highcharts != "undefined") {
console.warn("Highcharts is already loaded, not reloading");
this.createChart();
}else {
loadScript(this, Highcharts_ZIP + '/highcharts713.js')
.then(() => {
this.createChart();
})
.catch(error => {
let message = "Unknown error loading Highcharts";
if (error) {
message = error.message;
}
this.dispatchEvent(
new ShowToastEvent({
title: 'Error loading Highcharts',
message: message,
variant: 'error',
}),
);
})
}
You can find more information on using third-party libraries both on Lightning Web Components and Aura components here:
Lightning Web Component: Use Third-Party JavaScript Libraries
Our independent tech team has been servicing enterprise clients for over 15 years from our HQ in Bristol, UK. Let’s see how we can work together and get the most out of your Salesforce implementation.