There's a similar post already, but I don't feel it answers my particular question well enough.
I want to check that an external stylesheet has loaded. For example, if it has been stymied by a network problem then I want to know and load a fallback. This is as a fallback for a CDN for jQuery's themes CSS but I'd prefer this doesn't end up being specifically about that as I've other external CSS I use that I'd like to apply this to as well.
- The reference
link
element will be there on the page, so pattern matching for the existence of the link element in the head is not acceptable. - I do not have the ability to change the CSS in the stylesheet, so adding dummy CSS is not acceptable.
- Since I'm not in control of the CSS in the external stylesheet, relying on existing classes in the CSS is fragile, so I'd prefer if there is another solution.
- Is using a timeout the only way? How long should I set for it? What event should I choose to measure the time?
- I'd prefer pure javascript, then jQuery, but answers for other javascript frameworks will be accepted since they'll no doubt be helpful to someone.
Edit: A new thought. What about if the stylesheet was loaded via AJAX, and the status code checked? Is that a viable option, does anyone know?
Here's the script I have currently:
<script type="text/javascript">
var cdn = 'http://code.jquery.com/ui/1.10.1/themes/black-tie/jquery-ui.min.css';
var ss = document.styleSheets;
for (var i = 0, max = ss.length; i < max; i++) {
var sheet = ss[i];
var rules = sheet.rules ? sheet.rules : sheet.cssRules;
if (sheet.href == cdn) {
if ( rules == null || rules.length == 0) {
var link = document.createElement("link");
link.rel = "stylesheet";
link.href = '/js/jquery-ui/1.10.1/themes/black-tie/jquery-ui.min.css';
document.getElementsByTagName("head")[0].appendChild(link);
}
break;
}
}
</script>
What I've found on using the console (Chrome v25.0.1364.172) is that even when the stylesheet has loaded from the CDN, document.styleSheets[x].rules
is null
. I'm not sure if I'm accessing it correctly in the console though, maybe there's another function I should use or object?
CSSStyleSheet {rules: null, cssRules: null, ownerRule: null, media: MediaList, title: null…}
cssRules: null
disabled: false
href: "http://code.jquery.com/ui/1.10.1/themes/black-tie/jquery-ui.min.css"
media: MediaList
ownerNode: link
ownerRule: null
parentStyleSheet: null
rules: null
title: null
type: "text/css"
__proto__: CSSStyleSheet
If anyone can help me find how to check the stylesheet has loaded, that would be very helpful and much appreciated.