There is a similar post there already , but I don’t feel that it answers my specific question well enough.
I want to check if an external stylesheet is loaded. For example, if it was drowned out by a network problem, I want to find out and download a backup. It’s like a CDN reserve for CSS jQuery themes, but I would prefer that it doesn’t end with what it was, since I have another external CSS that I use, and I would like to apply that too.
- The reference
link element will be present on the page, so matching patterns for the existence of the link element in the head is unacceptable. - I have no way to modify CSS in the stylesheet, so adding fake CSS is not acceptable.
- Since I don't control CSS in an external stylesheet, relying on existing classes in CSS, this is fragile, so I would prefer a different solution.
- Does timeout use the only way? How long should I do this? Which event should I choose to measure time?
- I would prefer pure javascript, then jQuery, but the answers to other javascript frameworks will be accepted, as they will no doubt be useful to someone.
Edit: A new thought. How about whether the stylesheet has been loaded via AJAX and the status code checked? Is this a viable option, does anyone know?
Here's the script I have:
<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 found when using the console (Chrome v25.0.1364.172) is that even when the stylesheet was loaded from the CDN, document.styleSheets[x].rules is null . I'm not sure if I am accessing it correctly in the console, maybe there is another function that I should use or an 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 verify that the stylesheet is loaded, this will be very helpful and much appreciated.
source share