0

I load some stylesheets dynamically via JavaScript into my application. In this stylesheets I have different CSS variables that I want to read / write from my JS.

Stylesheets that are embeded directly in the head tag are handled correctly. The CSS variable gets evaluated by CSS and is visible in JS.

Stylesheets that are loaded dynamically during runtime do have some strange error. The CSS variable gets evaluated by CSS but is not visible by JS.

Anybody have an hint?

Plunker with minimal demo of error:

https://plnkr.co/edit/EChqjvZQJp7yz3L6nknU?p=preview

Method I use to load the CSS dynamically:

var fileref = document.createElement("link");
fileref.setAttribute("rel", "stylesheet");
fileref.setAttribute("type", "text/css");
fileref.setAttribute("href", "not_embedded_from_start.css");

document.getElementsByTagName("head")[0].appendChild(fileref);

Method I use to read the CSS variable:

var cS = window.getComputedStyle(document.querySelector("html"));
var pV = cS.getPropertyValue('--foo');

Example CSS:

:root {
  --foo: green
}

#foo {
  background-color: var(--foo);
}
Sp0tlight
  • 409
  • 1
  • 4
  • 18

1 Answers1

2

That is because the stylesheet is not done loading at runtime, and therefore the CSS variable is not accessible to JS until later.

To do that, you simply attach an onload handler to your dynamically added stylesheet, so that it calls a function, say stylesheetLoaded(), when it is done loading (hence accessible to JS):

var fileref=document.createElement("link");
fileref.setAttribute("rel", "stylesheet");
fileref.setAttribute("type", "text/css");
fileref.onload = function(){ stylesheetLoaded(); }
fileref.setAttribute("href", "not_embedded_from_start.css");

Note that it is strongly recommended to attach the onload handler before setting the href attribute.

And then you can execute whatever logic you want in that function call:

var stylesheetLoaded = function() {
  cS = window.getComputedStyle(document.querySelector("html"));
  pV = cS.getPropertyValue('--baz');
  document.getElementById("baz").innerText = pV;
}

See proof-of-concept fork of your code: https://plnkr.co/edit/OYXk7zblryLs3F5VM51h?p=preview

Terry
  • 63,248
  • 15
  • 96
  • 118