Skip to content

Instantly share code, notes, and snippets.

@rapsacnz
Created September 10, 2018 18:39
Show Gist options
  • Save rapsacnz/97390b4e02dd77b688daa976db25044e to your computer and use it in GitHub Desktop.
Save rapsacnz/97390b4e02dd77b688daa976db25044e to your computer and use it in GitHub Desktop.
Load up scripts using Promises in Lightning
getResouce: function(component, scriptName, resourceName) {
return new Promise($A.getCallback(function(resolve, reject) {
if (component.get("v.scriptsLoaded") == true) {
resolve(window[scriptName]);
}
else {
// Create script element and set attributes
var script = document.createElement('script');
script.type = 'text/javascript';
script.async = true;
script.src = resourceName;
var el = document.getElementsByClassName('scriptdiv')[0];
el.parentNode.insertBefore(script, el);
// Resolve the promise once the script is loaded
script.addEventListener('load', () => {
component.set("v.scriptsLoaded", true);
resolve(window[scriptName]);
});
// Catch any errors while loading the script
script.addEventListener('error', () => {
reject('script failed to load');
});
}
}))
},
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment