0

I have the following JavaScript in the <head> of a simple static page, which specifies either a.css or b.css as the stylesheet to use depending on the result of some additional JavaScript (useA(), not shown here).

<head>
   <script>
        var ss = document.createElement("link");
        ss.rel = "stylesheet";
        ss.href = (useA() ? "a.css" : "b.css");
        document.head.appendChild(ss);
   </script>
</head>

This results in a flash of unstyled content (FOUC) when I load or refresh the page on both Firefox and Chrome.

Using a plain <link rel="stylesheet" ...> doesn't have this problem: CSS loaded in <head> using <link> is apparently render-blocking. Is there some way to get the same behavior for CSS injected stylesheets as well?

Constraints:

I can't change a.css or b.css so I'm not looking for a solution which involves loading both stylesheets, or a combined styleseet and setting an indicator class on a root element to effect the choice between the sheets. I'm also not looking for visibility:hidden or display:none tricks which delay any display until the page is fully loaded.

BeeOnRope
  • 60,350
  • 16
  • 207
  • 386
  • >> I'm also not looking for visibility:hidden or display:none tricks which delay any display until the page is fully loaded.<< what exactly do you want to display until the a/b.css is loaded? If you're trying to mimic the render-blocking behaviour, isn't it just fine to `display:none` on the body until you're sure the css is loaded. You can attach a handler for that like `ss.onload = ()=> document.getElementsByTagName("body")[0].style.display = 'block';` – Lars Sep 07 '21 at 21:01
  • @Lars - yeah, I guess I'd like it to be like the render-blocking behavior. Nothing should be displayed until the CSS is parsed, and after that the body HTML can be displayed incrementally as usual with the correct styles. Most of the tricks I've seen with `display:none` defer the reveal until the document is fully loaded, which is different. Your suggestion to use the `onload` element of the style itself is a good one. – BeeOnRope Sep 07 '21 at 21:03

0 Answers0