[SalesForce] Load an external Javascript library in a Lightning Community

To add external Javascript library to a Lightning Community, we tried including it in HTML head markup options. Result: CORS errors. We have added the URL to a list of trusted sites but it did not help.

We then tried adding the Javascript library as a static resource and use it in a Lightning component via ltng:require scripts="{!$Resource.ResourceName}". The library did load but we weren't able to use it.

Best Answer

added based on comments

You should not use direct # (Id selector) and . (class selector) selectors in jquery (or any other library) as that will cross the component boundary. You should instead use $(component.find('initid').getElement()) which will respect component boundary.

Once the library is loaded $ is available throughout. Also there is no need of onready as you are already invoking the function on afterScriptsLoaded.

Below is the sample script:

COMPONENT:

<ltng:require scripts="{!$Resource.myscripts +'/jquery-3.4.1.min.js'}"
                       afterScriptsLoaded="{!c.scriptsLoaded}" />

<div>
    POC test jquery
</div>

<div aura:id="initid" class="initid">
    initid
</div>

<lightning:button label="Add Text" onclick="{!c.addText}" />
<div aura:id="dynamictext" class="dynamictext">
    dynamictext
</div>

CONTROLLER js:

scriptsLoaded : function(component, event, helper){
    console.log('handle scriptsLoaded load => ', $, jQuery);
    $(component.find('initid').getElement()).text('Added text during init');
},
addText : function(component, event, helper){
    $(component.find('dynamictext').getElement()).text('dynamic text from button');
}

Old answer

I just tested in my org with below code:

COMPONENT file:

<ltng:require scripts="{!$Resource.myscripts +'/jquery-3.4.1.min.js'}"
                       afterScriptsLoaded="{!c.scriptsLoaded}" />

<div>
    POC test jquery
</div>

CONTROLLER js:

scriptsLoaded : function(component, event, helper){
    console.log('handle scriptsLoaded load => ', $, jQuery);
}

And got below log:

handle scriptsLoaded load =>  ƒ (e,t){return new k.fn.init(e,t)} ƒ (e,t){return new k.fn.init(e,t)}

This means it is working in community - even when I login as community user.

Related Topic