views:

88

answers:

3

I just switched to start using a CDN for external images/static files for my site and I wanted to know how I could build a backup in case this CDN failed. Is there a way to reference an external link in an HTML/JavaScript file that would let you specify a fallback location for that file if it is unavailable in the first external host?

A: 

(Edited: First attempt was wrong)

<script src="some/remote/script.js">
    // Set a flag in the above script
</script>
<script>
    if ( ! flag ) {
        // This code runs if script.js fails to load for some reason
    }
</script>

<object data="http://cdn/file.png" type="image/png">
    <!-- You can nest objects in here too -->
    <img src="http://local/file.png" alt="Fallback Image"/>
</object>

So I suppose you could use the script method for everything; in the event the remote files fail to load, use the fallback code to change all paths to point to your backup server.

Ant P.
The script answer is wrong! (simple test under FF) - also see under http://www.w3.org/TR/REC-html40/interact/scripts.html#adef-src-SCRIPT it tells you that "If the src has a URI value, user agents must ignore the element's contents"
Dror
Guess I remembered wrong then.
Ant P.
+3  A: 

This first answer may not work in all browsers. You could just have some/remote/script.js set some variable "loaded=true" and then check it in the next script block.

<script>
loaded=false
</script>
<script src="some/remote/script.js"></script>
<script>
if(loaded==false){
  //do what you want here if it didn't load
}
</script>
+1  A: 

There's a good article on this here: http://happyworm.com/blog/2010/01/28/a-simple-and-robust-cdn-failover-for-jquery-14-in-one-line/

This came in handy for me on a site using the Microsoft Ajax CDN to get jquery. We had a few customers whose machines did not trust the SSL certificate from the CDN when we used jquery on HTTPS pages. A local fallback is a good way to fix that problem.

Jamey