Google Fonts Not Working in China – How to Fix it

We are using Google API to serve libraries such as jQuery and Web Fonts because it serves fast through Google’s reliable infrastructures. It is used almost everywhere, and so much so that some users may already have the cache stored in their browser, which makes the libraries load even faster.

Unfortunately, that is not the case in China. The China government closed access to many of Google’s services including Google API in 2014. Chances are that your website may appear partially broken in China because the jQuery and web fonts hosted in Google are inaccessible.

In this post, we will see how to bypass China’s "digital" Great Wall, so our website can run like it is viewed outside of China. We will be using an alternative font library that mirrors Google Fonts and libraries, but first, we will need to put in some measures to identify users who hail from China.

Identifying User Location

To begin with, we will need to find where our visitor is from and to do so, we will be using this WIPMania API that allows the retrieval of a visitor’s geolocation, including their country name:

$.getJSON('http://api.wipmania.com/jsonp?callback=?', function (data) { 
	swal('You are from', data.address.country);
});

We use jQuery $.getJSON to call the API. We then pass data.address.countrywhich should tell us where the visitor is from. Here is a demo.

Providing Alternative Web Font Source

So now that we can retrieve our visitor location, we’re going to replace Google Fonts with Useso libraries, a CDN service that mirrors Fonts and Libraries from Google API, to serve visitors from China.

At this stage, we still have our font styles pointing to Google API:

<link href='http://fonts.googleapis.com/css?family=Oswald:400,300,700' rel='stylesheet' type='text/css'>

We will replace the href within the link element with a JavaScript function.

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

This function replaces each link to refer to //fonts.useso.com/ in place of pointing to Google API address, //fonts.googleapis.com/.

The function will run only when the visitor is from CN, China’s international country code.

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

We are all set. Now, visitors from China will be served fonts via //fonts.useso.com/, which is not blocked by the Chinese government.

WebsiteFacebookTwitterInstagramPinterestLinkedInGoogle+YoutubeRedditDribbbleBehanceGithubCodePenWhatsappEmail