views:

173

answers:

4

I want to parse the CSS files that are loaded with an HTML page but I don’t want to make AJAX calls to reload the CSS files that have already been loaded. Is there any way to access the pages unparsed CSS text?

For example, it would allow one to access -moz-* declarations in Safari.

+2  A: 

I think you want to look at document.styleSheets.

Annie
document.styleSheets is the browsers parsed version of CSS. For example, a `-webkit-background-clip: border-box;` won’t show up at all in Firefox or IE.
mazniak
+1  A: 

Did you actually try to get it by AJAX? Most likely it will be loaded from browsers cache.

Ivan Nevostruev
Loading by AJAX always results in at minimum an HTTP request having to be sent and returned, plus the time to load the CSS file if the response code is not something like a 304. I really don’t want any extra latency as I want to modify some styles before the page loads.
mazniak
+5  A: 

You could load your CSS using AJAX.

  1. Load your CSS
  2. Parse the CSS
  3. Inject the CSS into the DOM (in full or in part)

This can be done using LazyLoad:

"LazyLoad is a tiny (only 1,541 bytes minified), dependency-free JavaScript library that makes it super easy to load external JavaScript and CSS files on demand."

Daniel Vassallo
If you follow this method, maybe you may split up your CSS in two: A static CSS file which does not require parsing, and a second one to be loaded through AJAX, and applied after your 'transformation'.
Daniel Vassallo
It’s too bad but this seems to be the only way to get ahold of the unparsed CSS source. I’d rather not incur the overhead of having to fetch via AJAX, but sometimes you have to do what you have to do…
mazniak
A: 

Ivan said:

Did you actually try to get it by AJAX? Most likely it will be loaded from browsers cache.

Mazniak said:

Loading by AJAX always results in at minimum an HTTP request having to be sent and returned, plus the time to load the CSS file if the response code is not something like a 304. I really don’t want any extra latency as I want to modify some styles before the page loads

I say... why not just override the styles you want to change? For example:

/* here is your normal css: styles.css */
body {
    color: black;    
}

/* and you want to switch to red text instead... */

/* dynamically add this on page load */
body {
    color: red !important;
}
nickf