Using External JavaScript Libraries In Aura Component
You may come to a scenario where you have to use an external JavaScript library inside your aura component.
Salesforce allows you to do this by adding the external library as a static resource file and adding it into your component by using ltng:require
We are bound to upload the library as a static resource because you can’t use JavaScript hosted on CDN in Aura Components due to the Content Security Policy.
The external javascript library should respect the lightning locker services and it could be that the external library may not work as expected due to the locker service enforcement.
Let’s try to use Jquery inside an Aura Component.
Using Jquery In Aura Component:
Please go to https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js
Save the content in a file and name it jQuery.js
Upload jQuery.js as a static resource with the name jQuery in your Salesforce org.
Please create an Aura Component name as MyJqueryComponent and save the following code.
<aura:component>
<ltng:require scripts = "{!$Resource.jQuery}"></ltng:require>
<lightning:button variant="neutral" label="Click Me!" title="Click Me" onclick="{! c.clickHandler }"/>
<div id="myDiv" class="myDiv">
Success is the sum of small efforts, repeated.
</div>
</aura:component>
In the above component mark up we are adding the jquery library using the ltng:require tag.
You can add multiple JS static resources by adding them as comma-separated values in the scripts attribute of ltng:require tag.
.THIS.myDiv{
border : solid rgb(0, 183, 255) 2px;
padding : 2rem;
margin : 2rem;
display: none;
}
({
clickHandler : function(component, event, helper) {
var obj = $("#myDiv");
obj.fadeIn("slow");
}
})
In the above handler method, we are using Jquery standard methods to fadeIn a div.
Below is the output when you preview this component inside an Aura App.
ltng:require tag supports the following events:
afterScriptsLoaded:
This is fired when all the scripts are loaded by the ltng:require tag.
beforeLoadingResources:
This is fired before ltng:require starts loading the resources.
You can use these events if you have a scenario to execute a piece of code before loading an external resource or after loading a script.
In the next part, we will be learning How to Debug Aura Components.
Thank you for visiting SalesforceBlue.com
If you have any queries feel free to write down a comment below 🙂
Top site ,.. amazaing post ! Just keep the work on !
This is quality work regarding the topic! I guess I’ll have to bookmark this page. See my website QH9 for content about Cosmetics and I hope it gets your seal of approval, too!