0

I'm currently implementing some embed widgets that people can insert into their websites. These blocks need CSS to give format to the HTML.

I'm including the stylesheets by appending the link tag in the head of the document but this only guarantee that the browser will start retrieving the stylesheet.

My problem is not about performance, my problem is that HTML loads before the stylesheet is downloaded and is shown with the default styles until browser downloads the stylesheet (sometimes this can take seconds if the connection is low, like mobile connections).

How can I control the moment when the stylesheet is downloaded and parsed? My aim is to hide content and show it when the stylesheet is totally loaded. The ideal way would be a callback function.

Thanks in advance.

Notes: I need something like async loading of images. Javascript allows loading images asynchronously with a callback function when is completely downloaded so you can show a loading spinner or hide it until is totally loaded.

Iman Bahrampour
  • 6,180
  • 2
  • 41
  • 64
  • Don't do that. People can read unstyled content. If there is nothing displayed they are more likely to just give up and go away. – Quentin Dec 12 '17 at 10:08
  • 1
    Possible duplicate of [How to check if all CSS files have been downloaded to insert HTML using JavaScript?](https://stackoverflow.com/questions/12532344/how-to-check-if-all-css-files-have-been-downloaded-to-insert-html-using-javascri) – George Dec 12 '17 at 10:08
  • Thank you George, I will check it, looks quite similar at first sight. – José Manuel Blasco Dec 12 '17 at 10:14
  • you can simply create and add the style tag with js and use the onload with a callback to show the html ;) something similar to `var style = document.createElement('style'); style.type='text/css'; style.onload = function() { ... };` – Roberto Bisello Dec 12 '17 at 10:25
  • @RobertoBisello — Style elements don't have load events, nor do they load CSS from an external file. – Quentin Dec 12 '17 at 10:32
  • ops! mistype, I meant "link" not "style", but now I see that this solution is not supported by all browsers, so it's not really useful... – Roberto Bisello Dec 12 '17 at 10:41
  • Thanks to all! I'll try the AJAX solution and I tell you how has it been. (solution mentioned in https://stackoverflow.com/a/12570092/3411285 response). – José Manuel Blasco Dec 12 '17 at 10:45

0 Answers0