Skip to content

Instantly share code, notes, and snippets.

@Dobby89
Last active July 16, 2020 07:21
Show Gist options
  • Save Dobby89/f9d12f2b257e447d068981cb9f21af27 to your computer and use it in GitHub Desktop.
Save Dobby89/f9d12f2b257e447d068981cb9f21af27 to your computer and use it in GitHub Desktop.
DOM utils / helpers
export function injectScriptTag(src: string, id: string): Promise<boolean> {
// eslint-disable-next-line consistent-return
return new Promise((resolve, reject) => {
if (document.getElementById(id)) {
// Already exists
return resolve(true);
}
const allScripts = document.getElementsByTagName('script');
const lastScriptTag = document.getElementsByTagName('script')[
allScripts.length - 1
];
const scriptTag = document.createElement('script');
scriptTag.id = id; // To avoid inserting the same thing more then once
scriptTag.onload = function () {
return resolve(true);
};
scriptTag.onerror = (error) => {
return reject(error);
};
scriptTag.src = src;
if (lastScriptTag && lastScriptTag.parentNode) {
lastScriptTag.parentNode.insertBefore(
scriptTag,
lastScriptTag.nextSibling
);
}
});
}
export function injectStyleTag(href: string, id: string): Promise<boolean> {
// eslint-disable-next-line consistent-return
return new Promise((resolve, reject) => {
if (document.getElementById(id)) {
// Already exists
return resolve(true);
}
const headEl = document.getElementsByTagName('head')[0];
const linkTag = document.createElement('link');
linkTag.id = id; // To avoid inserting the same thing more then once
linkTag.rel = 'stylesheet';
linkTag.type = 'text/css';
linkTag.onload = function () {
return resolve(true);
};
linkTag.onerror = (error) => {
return reject(error);
};
linkTag.href = href;
linkTag.media = 'all';
headEl.appendChild(linkTag);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment