Created
September 10, 2018 18:39
-
-
Save rapsacnz/97390b4e02dd77b688daa976db25044e to your computer and use it in GitHub Desktop.
Load up scripts using Promises in Lightning
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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