We need to use myResource.js file with helloWorld() function that we have downloaded into "static resource." We need to call helloWorld() on button clicks and some other events.

I've created simple lightning component trying to implement the above.

afterScriptLoaded is Not needed in our case. I need to call helloWorld() in myResource.js on button click.

helloWorld() --- does Not get called, no errors

This lightning component is used on Community page.

I did see How do I call functions loaded from a Static Resource JavaScript file? and many other posts, but are there any other ways to resolve it besides "attach your utility methods to the global window object(SecureWindow)"? And does it work Only with 'afterScriptLoaded' ?

Please see my code below and let me know what is wrong. Many thanks


<aura:component implements="forceCommunity:availableForAllPageTypes" access="global">      

    <ltng:require scripts="{!$Resource.myResource }"/>      

    <lightning:button label="Test1" onclick="{! c.callJsFunction }"  />    


Controller myTest.js

    callJsFunction: function(component, event, helper) {

    helloWorld();  // does Not get called

    //alert("Inside callJsFunction");  // works


1 Answer 1


See Sharing JavaScript Code Across Components. You need to export your functions to the window object.

are there any other ways to resolve it besides "attach your utility methods to the global window object(SecureWindow)"

No, this is the officially sanctioned method for sharing JavaScript across components.

And does it work Only with 'afterScriptLoaded'

You don't need to use afterScriptsLoaded, but be aware that the function will not be available before afterScriptsLoaded is called. If you're loading a lot of code, use afterScriptsLoaded to stop displaying a spinner that you should display while your component is loading.

Obligatory example follows.


window.helloWorld = function() {
    alert("Hello World");


<aura:application >
    <ltng:require scripts="{!$Resource.helloWorld}" />
    <ui:button press="{!c.hello}">Hello World</ui:button>


    hello: function(component, event, helper) {

Methods you define in your code that are not attached to window can be called from within the closure that's created, but not outside of it. In order for your methods to be accessible, you have to "export" them. Standard JavaScript uses methods like exports or amd. However, those are not consistent nor necessarily familiar to developers. In Lightning, the officially documented method is to use the window object.

You must log in to answer this question.

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