Use Third-Party JavaScript Libraries In Lightning Web Component
In order to use the external Javascript libraries in Lightning Web Component, you have to download the library from the third-party library’s site and then upload the library to your Salesforce organization as a static resource, which is a Lightning Web Components content security policy requirement.
In order to understand this with an example, we will be using the jQuery library. Please download and upload it as a static resource file in your org with the name jQuery.
import { LightningElement } from 'lwc';
import jQuery from '@salesforce/resourceUrl/jQuery';
import { loadScript } from 'lightning/platformResourceLoader';
export default class JqueryDemo extends LightningElement {
renderedCallback() {
console.log('jQuery:', jQuery);
loadScript(this, jQuery).then(
()=> {
console.log('Jquery loaded');
});
}
greetingHandler() {
console.log($("p"));
$(this.template.querySelector('p')).fadeIn();
}
}
At Line 2 we are importing the library by its static resource name
At Line 3 we are importing the loadScript from the platformResourceLoader module.
At Line 9 we are loading the library by invoking the loadScript function. Please note that we are loading the script once the component is rendered. Thus, the loadScript function is invoked under renderedCallback()
<template>
<lightning-card title="jQueryDemo">
<lightning-button variant="brand" label="Click Me" title="click Me" onclick={greetingHandler} slot="actions"></lightning-button>
<p class="slds-p-horizontal_small" style="display:none;">
Hey! Have an awesome day :)
</p>
</lightning-card>
</template>
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="helloWorld">
<apiVersion>52.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
<target>lightning__RecordPage</target>
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>
Add this component to a lighting app page and check the output by clicking the button. You will get an output like the below:
Thank you for visiting SalesforceBlue.com
If you have any queries feel free to write down a comment below 🙂