How to implement a CDN failsafe for css files?

扶醉桌前 提交于 2020-01-04 14:31:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!