Switching between Youku and YouTube based on whether you're in China

Here is the JavaScript we are going with:

$(document).ready(function (){
    var country = '',
    youku = $('#youku');

    $.ajax({
        url: "https://ipinfo.io",
        dataType: "jsonp",
        success: function(response){
            var country = response.country;

            if(country != 'CN') {
                youku.attr('src','https://www.youtube.com/embed/K3cEE5h7c1s')
            }
         },
         error: function(){
            console.log('sorry...')
         },
         timeout: 5000
    });     
});

We are including the Youku link in the HTML and switching to YouTube if country is not China. This still works if connecting to ipinfo.io times out, which sometimes happens in China.

Edit: revised to add a 5 second timeout.

Edit2: We implemented this as an open source Wordpress plugin, in case others are interested. https://github.com/cncf/china-video-block


It is better to specifically check if YouTube is blocked in user's network rather than filtering out country based on IP which is never 100% reliable. This way it will even work in any school/office environment where YouTube could be blocked by network administrator for any reason.

This is the best answer I could find in this regard which tries to load the favicon of YouTube via JavaScript. If it succeeds to download that tiny image, YouTube is accessible. The image is only 0.2 kilobytes of download and it is most likely already cached by any user who ever visited YouTube.

That means the result is almost instantaneous for users with YouTube access and will take few seconds for users with blocked firewalls. The code is simple:

jQuery(function(){
    var youku = jQuery('#youku');
    var image = new Image();
    image.onload = function(){
        youku.attr('src','https://www.youtube.com/embed/K3cEE5h7c1s')
    };
    image.onerror = function(){
        youku.attr('src','https://www.youku.com/embed/K3cEE5h7c1s')
    };
    image.src = "https://youtube.com/favicon.ico";
});

This one is a better solution than stated above as it does not wait for document.ready event of jQuery, the image starts to load instantly.

(function(){
    var image = new Image();
    image.onload = function(){
        jQuery(function(){
            jQuery('#youku').attr('src','https://www.youtube.com/embed/K3cEE5h7c1s')
        });
    };
    image.onerror = function(){
        jQuery(function(){
            jQuery('#youku').attr('src','https://www.youku.com/embed/K3cEE5h7c1s')
        });
    };
    image.src = "https://youtube.com/favicon.ico";
})();

Update based on comments:

In case there is possibility of the image being cached previously on user's computer, adding the current timestamp parameter to the image URL will ensure the image is loaded despite previously cached.

    image.src = "https://youtube.com/favicon.ico?_=" + Date.now();