Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning metadata with CSS

I have a CSS stylesheet that's dynamically created on the server, and returned via a <link> tag. Is it possible to return any metadata with this stylesheet, that I could read with JavaScript?

(The use case: the stylesheet I return is a combination of several smaller ones. I want my JavaScript code to be able to detect which smaller ones were included.)

I considered adding some custom properties to an element:

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

But when I try to read these with:

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

they're not returned. Any other ideaas?

EDIT: I ended up taking a slightly different approach. Instead of adding a <link> tag, I made an AJAX request to get the stylesheet, and added its text to a <style> tag. This way I could use the HTTP response headers to include metadata. Of course, this won't work across domains, like a <link> tag does.

like image 249
JW. Avatar asked May 06 '11 23:05

JW.


1 Answers

See example of the following →

Though I think this technique is ill-advised, here's something I developed that I've tested to work in Chrome, FF, Safari and IE8.

First, I picked the list-style-image property to be used to store the meta data since it can contain any string in the url() parameter and yet wasn't going to be used under any normal circumstances in the body CSS.

Then I implemented a common cross-browser function to getComputedStyle since this isn't available in all browsers.

Then I parsed the return property to get only the data within the 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 more than one piece of information you could comma-delineate the data or potentially even store a JSON string. I hope you have a good reason for wanting to do this as I think there are better ways to store meta data... but there you go!

See example →

like image 129
mVChr Avatar answered Oct 24 '22 03:10

mVChr