Skip to content

Instantly share code, notes, and snippets.

@josephm28
Created March 13, 2019 21:22
Show Gist options
  • Save josephm28/d3b19c906aee7a268dd28d71215427d1 to your computer and use it in GitHub Desktop.
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
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");
});
}
@scbj
Copy link

scbj commented May 27, 2021

The onload listener is not triggered for link tag (unlike script tag) 😕

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