Skip to content

Instantly share code, notes, and snippets.

@StoneyEagle
Created May 2, 2023 17:57
Show Gist options
  • Save StoneyEagle/490cee6ba0a427b3283c6f18f326577a to your computer and use it in GitHub Desktop.
Save StoneyEagle/490cee6ba0a427b3283c6f18f326577a to your computer and use it in GitHub Desktop.
Inject script or css into the dom
/**
* @param {string[]} filePaths - Array of file paths to append to the document
* @returns {Promise<void>} - Promise that resolves when all files have been appended
* @usage appendScriptFilesToDocument(['script.js', 'style.css'])
*/
const appendScriptFilesToDocument = (filePaths) => {
return new Promise((resolve, reject) => {
let count = 0;
const total = filePaths.length;
if (total === 0) {
resolve();
}
function appendFile(filePath) {
let file;
if (filePath.endsWith('.js')) {
file = document.createElement('script');
file.src = filePath;
} else if (filePath.endsWith('.css')) {
file = document.createElement('link');
file.rel = 'stylesheet';
file.href = filePath;
} else {
reject(new Error('Unsupported file type'));
}
if (!file) return reject(new Error('File could not be loaded'));
file.addEventListener('load', () => {
count++;
if (count === total) {
resolve();
} else {
appendFile(filePaths[count]);
}
});
file.addEventListener('error', (err) => {
reject(err);
});
document.head.appendChild(file);
}
appendFile(filePaths[0]);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment