0

Here is my situation

I am creating some website that loads JavaScript from CDN like Google/jscdn.com. But some of them were totally blocked in China. But 50% of my visitors are from China and the other are from other countries. Is it possible to load one more source if the particular one is blocked?

For example, if googleapis.com is blocked, I will load from lib.sinaapp.com which is accessible from China. And I want to load them in given order: try googleapis.com first then lib.sinaapp.com.

Is it possible to do this without server-side code?

Thanks

AGamePlayer
  • 7,404
  • 19
  • 62
  • 119

2 Answers2

0

You could use a cdn fallback technique.

Example:

<script src="//ajax.aspnetcdn.com/ajax/jquery/jquery-2.0.0.min.js"></script>
<script>window.jQuery || document.write('<script src="js/jquery-2.0.0.min.js">\x3C/script>')</script>

There's a nice article about this.

shadeglare
  • 7,006
  • 7
  • 47
  • 59
  • This is a very good way. But the problem is that the CN government blocks the Google CDN host and somehow the request is in pending. So it'd take a very long time to execute the `$ || xxx` code. – AGamePlayer Jun 13 '14 at 10:38
  • Unfortunately, there's no way to know if the request is going to succeed or fail until it is complete. Perhaps you want a solution that checks Google, then times out and switches to another URL if there's no response after xx seconds? – Blazemonger Jun 25 '14 at 14:55
0

My suggestion is using a JavaScript file loader like RequireJS or YepNope.

They allow you to load JavaScript files dynamically and you can control when a file should be loaded.

Here is a simple implementation of your requirement with YepNope:

//assuming that your JavaScript file is script.js
//put this flag in both script.js files
var scriptLoaded = true;

//put this in your main JS file
yepnope([{
  load: 'http://googleapis.com/123/script.js', //load this one first
  complete: function () {
    if (!scriptLoaded) {
      yepnope('http://lib.sinaapp.com/123/script.js');  //if not already loaded, load this file
    }
  }
}]);
advncd
  • 3,787
  • 1
  • 25
  • 31