2

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?

NeoWang
  • 17,361
  • 24
  • 78
  • 126

1 Answers1

2

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.

gp.
  • 8,074
  • 3
  • 38
  • 39
  • Can the order of css application be guaranteed? If a second css B.css include the same class names to override the A.css, but the A.css fails to load and the backup is loaded after B.css is loaded, it overrides B, right? – NeoWang Apr 05 '14 at 13:28
  • 2
    css files are loaded synchronously. So, ordering would be A.css -> failed -> A-backup.css -> B.css. So there should not be any issue. Check the console log in http://jsfiddle.net/jJ4Yu/ This is based on observation not sure if this is really the standard behavior but worth a try. – gp. Apr 06 '14 at 03:04
  • 1
    On Chrome it is A.css->B.css->A-backup.css, at least in console. Perhaps a reliable way is to chain the loading of css with script callbacks, but that serializes the downloading, and is probably not worth it. – NeoWang Apr 06 '14 at 05:47