开发者

Fetching raw CSS file contents from a browser

Is there any way to fetch the raw contents of a CSS file?

Lets imagine that I wanted to fetch any vendor-specific css properties from a CSS file. I would need to somehow grab the CSS contents and parse the开发者_StackOverflow社区m accordingly. Or I could just use the DOM to access the rules of a CSS file.

The problem is that in while using the DOM, mostly all browsers (except for <= IE8) tend to strip out all of the custom properties that do not relate to their browser engine (webkit strips out -moz and -o and -ms). Therefore it wouldn't be possible to fetch the CSS contents.

If I were to use AJAX to fetch the contents of the CSS file, then if that CSS file hosted on another domain, then the same origin policy would break and the CSS contents could not be fetched.

If one were to use a cross-domain AJAX approach then there would only be a JSONP solution which wouldn't work since we're not parsing any javascript code (therefore there is no callback).

Is there any other way to fetch the contents?


If a CSS file is on the same domain as the page you're running the script on, you can just use AJAX to pull in the CSS file:

$.get("/path/to/the.css", function(data) {/* ... */});

If not, you could try using Yahoo! Pipes as a proxy and get the CSS with JSONp.

As for parsing, you can check out Sizzle to parse the selectors. You could also use the CSS grammar (posted in the CSS standards) to use a JS lex/yacc parser to parse out the document. I'll leave you to get creative with that.

Good luck!


No, you've pretty much covered it. Browsers other than IE strip out unknown rules from their object models both in the style/currentStyle objects and in the document.styleSheets interface. (It's usually IE6-7 whose CSS you want to patch up, of course.)

If you wanted to suck a stylesheet from an external domain you would need proxy-assisted-AJAX. And parsing CSS from would be a big nasty job, especially if you needed to replicate browser quirks. I would strenuously avoid any such thing!


JSONP is still a valid solution, though it would hurt the eyes somewhat. Basically, in addition to the callback padding, you would have to add one JSON property "padding" and pass the CSS as a value. For example, a call to a script, http://myserver.com/file2jsonp/?jsonp=myCallback&textwrapper=cssContents could return this:

myCallback("cssContents":"body{text-decoration:blink;}\nb{text-size:10em;}");

You'd have to text-encode all line breaks and wrap the contents of the CSS file in quotes (after encoding any existing quotes). I had to resort to doing this with a Twitter XML feed. It felt like such a horrible idea when I built it, but it did its job.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜