Handling CSS load failure
I've been spending some thinking time recently on how to best handle resource failure for a page.
Of course with JavaScript files there isn't much 'clever' stuff that you can do. If you're loading from a CDN we can do something like this (taken from the HTML5 Boilerplate project):
<!-- Grab Google CDN's jQuery, with a protocol relative URL; fall back to local if offline -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="local/jquery-1.6.1.min.js">\x3C/script>')</script>
However I haven't seen much documented on CSS failure.
If your page is a blog post or something similar then best practice would be to make sure your markup is good, so that the un-formatted version is still a very much readable, if only a little boring, do开发者_开发技巧cument.
But what if you don't want to fall back to Lynx style? There may be a good reason; for example your application is complicated and is very much dependant on your layout. In which case, showing the page with no stylesheet is probably worse for user experience than not showing it at all.
Therefore, I wondered if a solution such as this would work - and if any of you are using it (or something similar)?
- Add a helper class at the end of your CSS file
#test { line-height: 1; }
- Add this JavaScript at the end of your page
var el = document.createElement('div');
el.setAttribute('id', 'test');
document.body.appendChild(el);
var o = (el.currentStyle) ? el.currentStyle['line-height'] :
(window.getComputedStyle) ? document.defaultView.getComputedStyle(el, null).getPropertyValue('line-height') : null;
if (o !== '1px') {
document.body.innerHTML = '<p>Resources failed to load, a prettier message should go here</p>';
}
See this JS Fiddle for it all together.
Questions are
- Thoughts on the above?
- Are you using something like this?
- Do you think its a good pattern (note that I'm only advocating this for web apps that are reliant on their styles).
Your rule may not take due to user stylesheets or other browser settings overriding the rule you're testing on. line-height
seems especially vulnerable to this, plus also any rule that takes a length value runs the risk of returning a computedStyle
in a different unit to the one you expected, making the string comparison fail. (Not to mention the 1
/1px
confusion in your example.)
In general I think this needs to fail better. If you think styles haven't loaded, add a warning to the page by all means, but don't replace the whole page with an error, making it completely useless to someone who might have been able to at least try to use it. This fragility is bad for accessibility.
精彩评论