Here is the code:
- http://jsfiddle.net/salman/2hyYg/
- http://jsfiddle.net/salman/2hyYg/show/
You'll notice the alert(document.styleSheets[x].cssRules.length)
fails with a "security exception". Any workaround for this. I am asking because there are a couple of "CSS lazy loading" classes out there that use this feature to detect if the CSS document is loaded.
Also: is the security exception a correct behavior/does it conform to standards?
You can get that error when trying to read a stylesheet loaded from a different domain or server, or trying to read an @import rule.
For your purpose, just check the document.styleSheets.length .
As of 2013, you can set the "crossorigin" attribute on the <link>-Element to signal the browser that this CSS is trusted (https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link).
After that, you can access its rules via Javascript.
You are loading css-files from another domain, I guess that you are not allowed to modify cssRules for externally loaded css files.
see this: Accessing cross-domain style sheet with .cssRules
The stylesheet is there and works fine, you just cannot access the cssRules
property of the stylesheet because it is set to null by the browser.
The security error you get is due to the same origin policy - you are working on stylesheets from another domain, you will not have this problem if the stylesheets are hosted on the same domain your webpage is.
Try with condition: (IE workaround)
function aftermath(index) {
var css = document.styleSheets[index].rules || document.styleSheets[index].cssRules;
alert(css.length);
}
This is giving the error:
aftermath(document.styleSheets.length - 1);
If i set it to 0 all work fine...
The problem is that the css is not ready at this time, if you need to access
it, you need to do that in a second moment
Last edit:
If you whant keep css updated from source, you can use a php proxy for loading it:
<?php
$name = 'http://ajax.googleapis.com/ajax/libs/jqueryui/$_GET[version]/themes/$_GET[theme]/jquery-ui.css';
$fp = fopen($name, 'rb');
fpassthru($fp);
exit;
?>
Then you can get it using e.g. /proxy.php?version=1.7.0&theme=humanity
You can put the failing line in a try-catch block. That's how i solved the same issue on one project.
Try window.document.styleSheets[x].cssRules.length
instead of document.styleSheets[x].cssRules.length
. It will work on firefox without any security exception.