JavaScript - Dynamically loaded CSS: CSS variables are not immediately accessible to JavaScript, but are successfully evaluated within the CSS itself

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);
}

Answer №1

The reasoning behind this issue is due to the fact that the stylesheet has not finished loading during runtime, resulting in the CSS variable being inaccessible to JavaScript until a later point.

To address this, you can easily add an onload event handler to the dynamically inserted stylesheet. This event handler will trigger a function, like stylesheetLoaded(), once the stylesheet has fully loaded and is accessible to JavaScript:

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

It's important to set the onload handler before defining the href attribute.

In the stylesheetLoaded() function, you can then implement any necessary logic based on the now-accessible CSS variable:

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

You can view a demonstration based on your code here: https://plnkr.co/edit/OYXk7zblryLs3F5VM51h?p=preview

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

It is impossible to resolve Npm vulnerabilities

My journey with learning React began when I decided to create my first app using the command: 'npx create-react-app my-app' However, upon building the app, I encountered a warning in the terminal: 22 vulnerabilities (9 moderate, 13 high) In ...

What could be the reason why I am unable to choose my radio button? What error am I

The output can be found here... I am struggling to use a radio button and cannot seem to select it. Can someone please explain what issue I am facing? Any help would be greatly appreciated. const [value, setValue] = React.useState({ yes:"", no:"" ...

Using a try block inside another try block to handle various errors is a common practice in JavaScript

In an effort to efficiently debug my code and identify the location of errors, I have implemented a try-catch within a try block. Here is a snippet of the code: for (const searchUrl of savedSearchUrls) { console.log("here"); // function will get ...

ng-include failing to retrieve file name containing UTF-8 character

I encountered an issue with the ng-include directive in the code snippet below. The file name it's trying to access contains a special character, specifically an ñ, resulting in a not found error being displayed. <div ng-include="'{{mainCtrl ...

Accept only numerical values, addition and subtraction symbols, commas, the F5 key, and various other characters

I want to restrict key strokes to only numbers (including those on the numpad), minus (-) and plus (+) signs, and commas (,). Currently, it types twice when I input a number (e.g. 2 is displayed as 22) and replaces the current value with the new number. F ...

Use jQuery to add and remove classes while opening and closing div elements individually

I am working on a page that contains hidden fullscreen divs. My goal is to be able to open these divs individually by clicking on the corresponding button and close them by clicking the "close" button inside the div. Currently, I am able to open a div suc ...

When a two-sided object is rotated on the y-axis in THREE.js, the graphic vanishes into

class Game extends backbone.View constructor: -> @scene = new THREE.Scene() @camera = new THREE.PerspectiveCamera 75, window.innerWidth/window.innerHeight, 1, 100000 @camera.position.z = 300 @scene.add @camera ...

JavaScript MP3 player

Could someone kindly point out where I went wrong? I am attempting to create an MP3 player using CSS, HTML, and JavaScript. Currently, the script only functions to start or stop the audio file. However, I keep encountering an error message: TypeError: docu ...

Tips for stopping the background color from affecting the text color

I'm dealing with a situation where I have an h6 nested inside a div. <div class="cylinder" data-v-5147e140=""> <div data-v-5147e140=""> <h6 class="quantite" data-v-5147e140="&qu ...

After combining two files in browserify, the error message "XXX.foo is not a function" appeared

When using browserify to bundle two JavaScipt files into one with the command: browserify X1.js X2.js --standalone XXX > bundle.js The file X1.js contains a function like this: function foo() { console.log("something") } And it is being exported i ...

Implementing React and Material UI: Maximizing Vertical Space Usage for a Box Component

Currently, I am working on a web application using React combined with Material UI. Within my code snippet below, you will see three Box components in play. Box 1 and Box 3 have specific heights set, but I am looking for a way to make Box 2 occupy the re ...

potential issues with memory leakage and browser crashes in three.js

Currently working on an app that features a spherical panorama photo with a jpg size of around 4Mb. Throughout the development process, I find myself constantly refreshing the page to see changes and browsing through various three.js example pages for insp ...

Creating a pull-up toolbar with just HTML and CSS for an Android browser

I need to create a draggable toolbar on my mobile webapp that can reveal content beneath it. I want to achieve this using just HTML/CSS, without relying on touch/scroll events or libraries. To do this, I'm overlaying a scrolling element on top of the ...

Update all Vue component imports to include the .vue extension at the end

The Vue CLI has decided to no longer support extensionless imports, causing compatibility issues with certain VS Code extensions like Vetur. In order to address this issue, I require all default component imports from a .vue file to include the file exten ...

Passing props to component elements through slots in Vue.js

Trying to pass props from a component element that includes a slot PatientBooking.vue <user-profile :titlename="BOOKINGDETAIL"> <div class="block"> <div>Ereferral: 84884jjd</div> <div>Gender: Mal ...

Trouble getting Fontawesome icons to accept color props when using react functional components with tailwindcss

Issue I'm Facing I'm currently working on a project that involves using icons extensively. Instead of manually adding a Fontawesome icon in every script, I have created a functional component that handles the rendering of icons based on given pr ...

Load a distinct JSP file from the sidebar in JSP

I have an index.jsp file containing a sidebar: <div id="sidebar"> <li ><a href="create">Create</a></li> <li ><a href="view">View</a></li> <li ><a href="Delete">Delete</a></li> & ...

"Crafting a sleek card design using Material UI components in React JS

Exploring the world of material UI and looking to create a card with an image and footer. However, I'm facing challenges as there is no default option for adding a footer in the card. https://i.stack.imgur.com/xlxyb.png I want the image to be center ...

Adaptable Design for Smartphones

Currently in the process of creating a website for my brother with Joomla 3.4 and Bootstrap. This marks my first venture into building a responsive site, so I'm seeking guidance on essential elements to include in my CSS such as font sizes in specific ...

"Improving User Experience with React.js Serverside Rendering and Interactive Event Handling

Currently, I am in the process of learning how to utilize react.js but I am facing some challenges with using event handlers. Here's a question that has been lingering in my mind: Is it feasible to employ server-side rendering and automatically send e ...