Skip to content

Instantly share code, notes, and snippets.

@ankit-kumar-jat
Created August 31, 2022 10:08
Show Gist options
  • Save ankit-kumar-jat/160bab4d192020005804d3313882ca4d to your computer and use it in GitHub Desktop.
Save ankit-kumar-jat/160bab4d192020005804d3313882ca4d to your computer and use it in GitHub Desktop.
Load javascript file dynamically
/**
*
* @param {String} url scrip url
* @param {String} id id for script tag
* @returns promise
*/
const loadScript = (url, id) => {
return new Promise((resolve) => {
const existingScript = document.getElementById(id);
if (existingScript) resolve(true);
const script = document.createElement('script');
script.src = url;
script.id = id;
script.type = 'text/javascript';
script.onload = () => {
resolve(true);
};
script.onerror = () => {
resolve(false);
};
document.body.appendChild(script);
});
};
export default loadScript;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment