Created
May 2, 2023 17:57
-
-
Save StoneyEagle/490cee6ba0a427b3283c6f18f326577a to your computer and use it in GitHub Desktop.
Inject script or css into the dom
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @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