问题
For javascripts hosted on CDN, I can always add some scripts below it to check if it is loaded successfully:
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
if (!window.jQuery) {
var script = document.createElement('script');
script.src = "/js/jquery.min.js";
document.body.appendChild(script);
}
</script>
I also used some hosted css files, like bootstrap. How can I reiliably check if it is loaded on the web page, and provide a fail-safe if isn't?
-----EDIT--------
And, by the way, should I use:
document.body.appendChild(script);
or:
document.write("<scr"+"ipt>"...);
Which one guarantees execution order in all browsers?
回答1:
you could use onload
and onerror
events...
<link rel="stylesheet" type="text/css" href="cdnurl/styles.css"
onload="alert('loaded')" onerror="javascript:loadCSSBackup()" />
javascript:
function loadCSSBackup(){
var css = document.createElement("link")
css.setAttribute("rel", "stylesheet");
css.setAttribute("type", "text/css");
css.setAttribute("href", 'backup/styles.css');
document.getElementsByTagName("head")[0].appendChild(css);
}
regarding 2nd question, you should avoid using document.write. Appending to body or head as in the code above should be fine.
来源:https://stackoverflow.com/questions/22879099/how-to-implement-a-cdn-failsafe-for-css-files