Skip to content

Instantly share code, notes, and snippets.

@r17x
Last active December 18, 2018 07:45
Show Gist options
  • Save r17x/dfcdf19c81c23e10c29a08c1393d0b0d to your computer and use it in GitHub Desktop.
Save r17x/dfcdf19c81c23e10c29a08c1393d0b0d to your computer and use it in GitHub Desktop.
InjectScript
/**
* Simple Injection HTML Script resource
* @author [email protected]
* Example use:
* rel its experimental | maybe not work on some browser
* const scriptList = [
* {
* src: 'url',
* async: boolean,
* defer: boolean,
* rel: 'preload|prefetch'
* }];
*
* InjectScript.addScript(scriptList)
* InjectScript.removeScript(scriptList)
*/
export class InjectScript {
/**
* @param {array} scriptList
*/
static addScript(scriptList) {
scriptList.forEach((script, key) => {
script.id = `script:${key}`;
InjectScript.addToBody({ ...script });
});
}
/**
* @param {array} scriptList
*/
static removeScript(scriptList) {
scriptList.forEach((script, key) => {
script = document.getElementById(`script:${key}`);
script.parentNode.removeChild(script);
});
}
/**
* @param {object}
*/
static addToBody({ id, src, async, defer, rel }) {
const element = document.createElement("script");
element.src = src;
element.async = async;
element.defer = defer;
element.id = id;
document.body.appendChild(element);
}
}
@r17x
Copy link
Author

r17x commented Dec 18, 2018

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment