Created
March 13, 2019 21:22
-
-
Save josephm28/d3b19c906aee7a268dd28d71215427d1 to your computer and use it in GitHub Desktop.
Dynamically load CSS using JS, with a promise to know when the style has been loaded. Do it all in bulk
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
async loadCSSStyles(){ | |
return new Promise((resolve, reject)=>{ | |
const styleURLs = [...]; | |
await Promise.all(styleURLs.map(async style => await fetchStyle(style))); | |
resolve(); | |
}) | |
}) | |
const fetchStyle = (url) => { | |
//https://stackoverflow.com/questions/574944/how-to-load-up-css-files-using-javascript | |
return new Promise((resolve, reject) => { | |
let link = document.createElement("link"); | |
link.type = "text/css"; | |
link.rel = "stylesheet"; | |
link.onload = function() { | |
resolve(); | |
console.log("style has loaded"); | |
//Can add setTimeout to attempt to wait for the styles to be applied to DOM | |
}; | |
link.href = url; | |
//Uses jQuery, but can be VanillaJS | |
$(link).appendTo("head"); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The
onload
listener is not triggered for link tag (unlike script tag) 😕