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?

3
  • Why would you want to do that? Commented Jan 22, 2017 at 1: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? Commented Jan 22, 2017 at 1: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 Commented Jan 22, 2017 at 1:23

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.