Flaudre Flaudre - 9 months ago 55
CSS Question

Check if user is using browser located in China or not

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?


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

Disclaimer: I wrote and maintain userinfo.io