Sample JavaScript for Static Resource:
window.ExampleJS = ( function() {
return {
exampleMethod: function() {
console.log( 'Inside exampleMethod from External JavaScript' );
return 'Text from External JavaScript';
}
};
}());
Static Resource:
Lightning Web Component:
HTML:
<template>
<lightning-card>
<div class=”container” lwc:dom=”manual”></div>
<lightning-button variant=”brand” label=”Click” onclick={callExample}></lightning-button>
</lightning-card>
</template>
JavaScript:
import { LightningElement } from 'lwc';
import Example from '@salesforce/resourceUrl/ExampleJS';
import { loadScript } from 'lightning/platformResourceLoader';
export default class ExternalJavaScript extends LightningElement {
connectedCallback() {
loadScript( this, Example )
.then( () => {
console.log( 'Script Loaded Successfully' );
} )
.catch( error => {
console.log( 'Error is', JSON.stringify( error ) );
} );
}
callExample() {
console.log( 'Inside Call Example' );
let returnString = ExampleJS.exampleMethod();
const container = this.template.querySelector('.container');
container.innerHTML = returnString;
}
}
JS-meta.xml:
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>52.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__Tab</target>
</targets>
</LightningComponentBundle>
Output: