In order to import the external or third party js or CSS in to LWC, We have to import them into Salesforce as static resource first. Then we need to import that file using loadScript and loadStyle methods and by referring file path inside the static resource. We need to import loadScript and loadStyle methods from ‘lightning/platformResourceLoader’ module.
Syntax: import { loadStyle, loadScript } from ‘lightning/platformResourceLoader’;
loadScript and loadStyle. Both methods create and return promises, which can be chained or used in parallel. You control the load sequence of your scripts or styles.
loadScript(self, fileUrl): Promise
loadStyle(self, fileUrl): Promise
self – A reference to the component. The value must be this.
fileUrl – A string that contains the path to the JavaScript file. To build the string, concatenate the resourceName and the path to the file within the static resource archive.
If you have multiple files to load, Then use promise.all([]); When using promise.all(), Then() exeucted once all methods inside promise.all() executed.
Example: promise.all([loadScript(self, fileUrl), loadScript(self, fileUrl)]).then().catch();
Inside of then/catch you can implement resolve/reject function to write logic/call handlers.
If not, you can directly invoke loadScript() using then(). It will be like loadScript(self, fileUrl).then().catch();
Since these are scripts/css, You will be mostly loading these inside connectedCallback() or renderedCallback() depending on use case. Remember that renderedCallback exectutes multiple times whenever the component re-renders. Hence handle the logic to execute load methods first time only.