0

how to call a method of the loaded script function in the javascript? Ex: if I have loaded a script named ‘abc’. Now I want to call a method of the abc. Let the method be fgh. How do I call it in LWC?

1 Answer 1

2

As long as you are loading the script using the LWC resource loader then you simply call the function using its name. So, for a function fgh defined like:

function fgh() {
    console.log('called');
}

in a resource (script) loaded by the resource loader you call it by simply doing:

fgh();
4
  • Thanks @phil-w ,got it, to add ,below scenario. static resource contains -- example var x = function (a, b) {return a * b}; how can we call function assigned to variable
    – rahulsfdx
    Apr 6, 2020 at 15:56
  • That's an interesting issue. IIRC there is a scoping issue here because the script gets loaded into a container; I suggest you try this out and use the browser developer tools to examine what happens during the script loading. I seem to remember having similar issues a while back when creating a PoC...
    – Phil W
    Apr 6, 2020 at 16:32
  • 1
    @rahuldeshmaane You have to either attach the function to global scope (window), or use the export keyword (export { x as fgh };). Otherwise, that function is local to the file and cannot be accessed outside of it. Note: This is a JavaScript behavior, and not an inherent limitation of LWC.
    – sfdcfox
    Apr 6, 2020 at 16:33
  • Thank you Phil and @sfdcfox, appreciate your comments, let me try these recommendations and get back to the same thread in case i get solution.
    – rahulsfdx
    Apr 6, 2020 at 16:40

Not the answer you're looking for? Browse other questions tagged .