Check if user is using browser located in China or

2019-07-03 15:14发布

问题:

China is blocking Google API since 2014, this means long loading times for websites that include Map API or Fonts API. There is a workaround for this, since fonts.useso.com also provide the same font library (see libs.useso.com, fonts.useso.com respectively).

The following code

<link href='http://fonts.googleapis.com/css?family=Open+Sans:300,400,600&subset=latin,latin-ext' rel='stylesheet'>

can be changed into

<link href='http://fonts.useso.com/css?family=Open+Sans:300,400,600&subset=latin,latin-ext' rel='stylesheet'>

and it will work fine in China.

But, what if I want to dynamically choose the source I want to load the API from, considering the location from where the user is visiting?

回答1:

You could use a third party service to determine the user location and switch your font.

For example, you can integrate userinfo.io which is free. In this case, the location is determined based on the IP address so if the Chinese person visits from Europe, he will be located in Europe and the google fonts will be loaded.

Insert this in your <head>:

<script type="text/javascript" href="//cdnjs.cloudflare.com/ajax/libs/userinfo/1.0.0/userinfo.min.js"></script>

<script type="text/javascript">
UserInfo.getInfo(function(data) {
  // the "data" object contains the info
  if (data.country.code == 'CN') {
    // load your fallback fonts
  } else {
    // Load your google fonts
  }
}, function(err) {
  // the "err" object contains useful information in case of an error
});
</script>

Disclaimer: I wrote and maintain userinfo.io



回答2:

Timezone will do the trick:

var offset = new Date().getTimezoneOffset();
if(offset/60 == -8){
    console.log('Hello from China!');
}

Note that this ignores clients with incorrect clock config, but can cover most scenarios.



回答3:

I stumbled over another solution, that I'd like to share. I think it's cool since no need to include the library but only get the info through an ajax request.

function replaceGoogleCDN() {
  $('link').each(function(){
    var $intial  = $(this).attr('href'),
        $replace = $intial.replace('//fonts.googleapis.com/', '//fonts.useso.com/');
        $(this).attr('href', $replace);
  });
}

$.getJSON('//api.wipmania.com/jsonp?callback=?', function (data) { 
  if ( data.address.country_code == 'CN' ) {
    replaceGoogleCDN();
  }
});

EDIT: Not an awesome solution though, if you are on https, since you cannot load from http source and wipmania seems to not have a valid ssl certificate.

Source



回答4:

Google fonts are now being hosted on servers in China removing the slow loading times. (As of August 2016) See my answer here for full description.