Including metadata in CSS

Is it possible to include metadata with a dynamically created CSS stylesheet that is returned via a <link> tag and read it with JavaScript?

(In my scenario, the stylesheet I return consists of multiple smaller ones, and I want my JavaScript code to be able to detect which smaller ones were included.)

I thought about adding custom properties to an element:

body {
  -my-custom-prop1:0;
  -my-custom-prop2:0;
}

However, when trying to access these properties using:

window.getComputedStyle(document.body)['-my-custom-prop1']

they are not returned. Any other suggestions?

EDIT: Upon further consideration, I opted for a slightly different approach. Instead of using a <link> tag to retrieve the stylesheet, I made an AJAX request to fetch the stylesheet's text and added it to a <style> tag. This allowed me to leverage HTTP response headers to include metadata. Keep in mind that this method may not work across domains, unlike a <link> tag.

Answer №1

Check out an example of the following →

Although I believe this approach is not recommended, here is a method I have developed and tested in Chrome, Firefox, Safari, and IE8.

Initially, I selected the list-style-image property to store metadata since it can hold any string within the url() parameter without conflicting with normal CSS rules.

I then created a cross-browser function for getComputedStyle since it may not be available in all browsers.

The next step involved parsing the returned property to extract only the data enclosed within url(''), resulting in these functions:

var getStyle = function(el, cssprop) {
    if (el.currentStyle) {
        return el.currentStyle[cssprop];
    } else if (document.defaultView && document.defaultView.getComputedStyle) {
        return document.defaultView.getComputedStyle(el, "")[cssprop];
    } else {
        return (el.style) ? el.style[cssprop] : 0;
    }
};

var pullCSSMeta = function() {
    var aMeta = getStyle(document.body, 'listStyleImage').split('/'),
        meta = aMeta[aMeta.length - 1];

    return decodeURIComponent(meta.substr(0, meta.length - 1).replace(/"$/,''));
};

If you need to store multiple pieces of information, consider comma-separating the data or using a JSON string. Keep in mind that there are likely better alternatives for storing metadata, but feel free to explore this option!

View the example here →

Answer №3

Some time back, I inquired about a similar issue. It seems the only way to handle it is by manually parsing the stylesheet text using JavaScript. After realizing the complexity of this task, I chose to explore other options and eventually found a different solution. Perhaps utilizing clever techniques like applying standard properties to irrelevant classes could also be an effective approach.

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

What are the steps for generating a diagram using Chart.js?

I'm attempting to use Chart.js to create a specific diagram. Current Challenges: The point on the x-axis should be centered within the categories. I would like the value to appear above the point. https://i.sstatic.net/FFFr1.png This is what my co ...

Submit a HTML form to a Telegram recipient

I am looking to send HTML form data, which includes input values and select options, to a telegram user. After some research, I discovered that I need to create a Telegram bot. I successfully created one using @botFather by following these steps: /newbot ...

Struggling to retrieve data from a MongoDB database in JSON format via an API call? If you're working with JavaScript, Node.js, Express, and MongoDB, we can help you

Below is how I establish the connection to the database: > // Connecting MongoDB using MongoClient > > const MongoClient = require('mongodb').MongoClient > > const url = 'url is used' > > const dbName = 'vir ...

Can you provide some guidance on accessing HTTP headers while using Promises to make AJAX requests?

Currently, I am working on resolving jQuery ajax requests using bluebird.js and I have found it quite challenging to access the HTTP headers of the request. Here is a snippet of the code I am working with: Promise.resolve($.get(...)).then(function(data){ ...

The MediaMetadataRetriever with Android only provides the video date on the Galaxy S7

I am currently working on extracting the creation date and time of a video from its metadata. To achieve this, I am using the following code snippet: MediaMetadataRetriever retriever = new MediaMetadataRetriever(); retriever.setDataSource(path_to_video); ...

Is there a way to display the JavaScript widget exclusively on the homepage or main page

How can I limit the display of a Twitter widget on my blog page to only show on the main page and hide it when visitors navigate to sub-pages or individual blog entries? ...

Adjust the position of an object in Three.js based on the scale of another object

Sharing a helpful solution for a recent problem I faced in case it can assist someone else. Imagine you have a House object with a Chair inside it positioned in a particular spot. If you scale the House's size by 2, the Chair will no longer be in the ...

Tips for setting a specific height for an HTML table

For some reason, I can't seem to control the height of this table. I've set it to a maximum of 20px but all the rows are still showing. Here is the CSS: table { border:1px solid black; overflow:hidden; height:20px; max-height:20 ...

Develop a custom npm package with dependencies stored locally and add it to a different package during installation

I have developed three unique custom modules. getcorrespondence-1.0.0.tgz getrediscache-1.0.0.tgz setrediscache-1.0.0.tgz These custom node modules were created using the command npm pack. The module getcorrespondence-1.0.0.tgz has dependencies on two o ...

Tips for retrieving the location of a draggable waypoint in the Google Directions output

<!DOCTYPE html> <html> <head> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Location Partner</title> <!--styles for ...

The order of execution in AngularJS: Understanding the flow

I have taken over the responsibility of managing someone else's website, and while going through the codebase, I came across a snippet that looks like the one below (with some code omitted for simplicity): var Application = (function ($, global) ...

Creating a unique seal, badge, or widget in Django is a fun and rewarding project

Here are some examples of what I want to accomplish: View the gif showcasing the function Visit https://sectigo.com/trust-seal Check out another gif demonstrating the function Explore https://www.carandtruckremotes.com/ Don't miss this gif showin ...

Having difficulty with express.index when trying to send a JSON object

Express is my tool of choice for creating a simple web page. The code in my index.js file looks like this: exports.index = function(req, res){ res.render( 'index', { title: 'Expressssss', Tin: va ...

Guide on integrating a RESTful API within a router using the Express framework

I am trying to fetch data from the following link: using express.js. I have developed a Single Page Application website using react.js for the frontend, so I need to make a call to this route : /shipping/check/cost in my backend to retrieve the required ...

Creating a versatile function to verify the presence of empty values

Looking to validate fields for emptiness in a router, with potential use in other routers as well. How can I create a single function to handle this task? To see how it operates: , Desiring something similar to: , ...

Simple Method To Dynamically Align jQuery LightGallery Thumbnails On a Responsive CSS Website

Can anyone assist me quickly? I've implemented everything but am facing a slight issue with the centering of my ul code. I've tried various solutions without success. Here is my code, any advice would be greatly appreciated (I may sound stressed ...

Problem with stacking order in Internet Explorer 7

Our current issue involves a z-index problem with a div that should be positioned above another specific div. The div in question, named (house-over-banner), is set to absolute positioning, while the one below it is relative. Interestingly, everything dis ...

`<picture> contains the main image``

Is it possible to access the currently displayed source of a <picture> element in JavaScript without relying on viewport width or pixel density? Looking for a method similar to <select>:selected If anyone has insights on this, please share! ...

NodeJS Express REST API fails to fetch data in GET request

As I work on developing a REST API using NodeJS and Express, I have set up routes for handling "offers". However, when attempting to send a GET request, I receive an empty response along with a 200 status code. Here is the snippet from routes.js: route ...

Suggestion for React onmouseover functionality

Currently, I am in the process of learning how to build a website using React and Bootstrap CSS. In my project, I have incorporated a carousel and a separated navigation bar. Below is an example of the code for my carousel: class Home extends React.Compon ...