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.
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 →
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With