Using External JavaScript Library And Its Method In Lightning Component
In this blog we are going to learn about how to use external JavaScript and its method in lightning component. First, we learn how to use external JavaScript library in lightning component.
JavaScript Library
Following steps are used to load the external Java Script library in lightning component.
- Load your external java script library in static resource. Goto >> SetUp>> Custom Code >> Static Resources
- Use <ltng:require> tag to load the Java Script library in lightnig component as follows.
<!-- For one js library --> <!-- Here filename1 is static resource name --> <ltng:require scripts="{!$Resorce.filename1}"></ltng:require> <!-- For more than one js file --> <!-- Here filename1 and filename2 is static resource name --> <ltng:require scripts="{!join(',', $Resource.filename1, $Resource.filename2)}"></ltng:require>
Example
In this example we print the list of fruits which is predefined in external JavaScript library.
1). Create a js file as follows:
/** * Webkul Software. * * @category Webkul * @author Webkul * @copyright Copyright (c) 2010-2016 Webkul Software Private Limited (https://webkul.com) * @license https://store.webkul.com/license.html */ window._map = (function() { var fruits = ["Mango", "Apple", "Banana", "Graps", "Pineapple"]; return { getFruits: function() { return fruits; } }; }());
2). Upload the external js file/library in static resource. Goto >> SetUp>> Custom Code >> Static Resources
3). Create a lightning component and write following code.
<aura:component > <!-- /** * Webkul Software. * * @category Webkul * @author Webkul * @copyright Copyright (c) 2010-2016 Webkul Software Private Limited (https://webkul.com) * @license https://store.webkul.com/license.html */ --> <ltng:require scripts="{!$Resource.fruits}"></ltng:require> <aura:attribute name="externalList" type="Array" ></aura:attribute> <div> <p> Click on button to show the name of fruits...</p> <lightning:button label="Show Fruits" variant="brand" onclick="{!c.getFruits}"> </lightning:button> <aura:iteration items="{!v.externalList}" var="el"> <p> {!el}</p> </aura:iteration> </div> </aura:component>
4). Controller code.
({ getFruits : function(component, event, helper) { var fruits = _map.getFruits(); // Get the list of fruits from external Java Script Library console.log(fruits); component.set("v.externalList", fruits); } })
Support
That’s all for How To Use External Java Script And Its Method In Lightning Component , still if you have any further query or seek assistance to make your salesforce classic apps compatible with lightning experience, feel free to contact us, we will be happy to help you https://wedgecommerce.com/contact-us/.