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?
views:
88answers:
3(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.
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>
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.