Skip to content

Instantly share code, notes, and snippets.

@Haprog
Created January 17, 2018 03:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Haprog/c4bc03b465d8c0c0137ca96485d50b41 to your computer and use it in GitHub Desktop.
Save Haprog/c4bc03b465d8c0c0137ca96485d50b41 to your computer and use it in GitHub Desktop.
Utility methods for loading a script.
/**
* Load the given script.
* (appends a new <script> tag to the end of the main document's <head> tag)
*
* @param {string} src URL if the script to be loaded
* @param {?Object} props Properties to be set on the script (e.g. async, defer, onload, onerror)
* @param {?Object} attrs Attributes to be set on the script (e.g. id, data-*)
* @returns {Promise}
*/
let loadScript = (src, props, attrs) => new Promise((resolve, reject) => {
const script = document.createElement('script');
script.src = src;
for (const prop in props) {
script[prop] = props[prop];
}
for (const attr in attrs) {
script.setAttribute(attr, attrs[attr]);
}
script.addEventListener('load', () => resolve(script), false);
script.addEventListener('error', () => reject(script), false);
document.head.appendChild(script);
});
/**
* Load the given script.
* (appends a new <script> tag to the end of the main document's <head> tag)
*
* @param {string} src URL if the script to be loaded
* @param {?Object} props Properties to be set on the script (e.g. async, defer, onload, onerror)
* @param {?Object} attrs Attributes to be set on the script (e.g. id, data-*)
*/
let loadScriptLegacy = (src, props, attrs) => {
const script = document.createElement('script');
script.src = src;
for (const prop in props) {
script[prop] = props[prop];
}
for (const attr in attrs) {
script.setAttribute(attr, attrs[attr]);
}
document.head.appendChild(script);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment