0

I have a function that loads multiple CSS files

function loadCSS(stylesheets) 
{ 
  for( i = 0; i < stylesheets.length; i++ )
  {
      var stylesheetEl = document.createElement("link");
          stylesheetEl.rel   = "stylesheet";
          stylesheetEl.type  = "text/css";
          stylesheetEl.href  = stylesheets[i];

      document.head.appendChild(stylesheetEl);
  }
} 

But there's no way to tell when they're all loaded because they aren't loaded synchronously.

So how can I load one file, wait for all of the CSS to load completely, go to the next file etc?

Marcus Holm
  • 417
  • 3
  • 7
  • 15
  • Why would you want to do that? – NineBerry Jan 22 '17 at 01:08
  • 1
    Rather than waiting for the next file, why not just create a promise to load the next one? I don't think there's a way for you to block (which is what you're talking about) until the load has completed. A simpler option may just be to download one CSS file, and then use an @import directive for the rest, though. I am slightly confused about why you would want to do this in JavaScript, when you can just put the files in your HTML? – PSGuy Jan 22 '17 at 01:20
  • If you have no restriction to use jquery, you have a solution here : [http://stackoverflow.com/questions/3498647/jquery-loading-css-on-demand-callback-if-done](http://stackoverflow.com/questions/3498647/jquery-loading-css-on-demand-callback-if-done) – scraaappy Jan 22 '17 at 01:23

1 Answers1

0

When you create those elements you will have to bind an event so that you can listen for the event when CSS is loaded and then load another one. I was going to post an example but I found one nice article explaining all the inner work. Please take a look at this article

nicholasnet
  • 2,117
  • 2
  • 24
  • 46