I am encountering an issue with dynamically loading stylesheets via JavaScript into my application. Within these stylesheets, I have various CSS variables that I need to access and modify from my JavaScript code.
When the stylesheets are directly embedded in the head tag, everything functions correctly. The CSS variables are evaluated by CSS and can be accessed in JS.
However, when dynamically loaded during runtime, a peculiar error occurs. While the CSS variable is being evaluated by CSS, it is not visible to JS.
Has anyone encountered a similar problem before?
Here is a Plunker demonstrating the issue:
https://plnkr.co/edit/EChqjvZQJp7yz3L6nknU?p=preview
This is the method I am using to dynamically load the CSS:
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);
And here is how I am attempting to read the CSS variable:
var cS = window.getComputedStyle(document.querySelector("html"));
var pV = cS.getPropertyValue('--foo');
Here is an illustrative example of the CSS:
:root {
--foo: green
}
#foo {
background-color: var(--foo);
}