Some countries (especially the People's Republic of China) strictly control access to various international web services. You can use service detection to determine whether particular services are available and fall-back gracefully or use alternative providers.
As well as from inside China, another common place where access to third-party services may be blocked is from behind corporate firewalls.
First, read this rule: Do you manage your 3rd party dependencies?. You should always start by carefully managing the number of 3rd party services and dependencies your application or website depends on.
When you have identified an essential 3rd party service, you need to plan how to respond when that service is not available. There are 2 main options:
Option 1: Fall-back gracefully
The site will attempt to use this service and include its features, but if this is not available, the rest of the site will continue to operate normally.
Option 2: Provide an alternative to the blocked service
If, for example, your site displays videos, you can detect that YouTube is not available in China and embed YouKu videos instead.
Both these options require service detection to operate properly. Remember that attempting to connect to a blocked service from China could take a long time to timeout, potentially adding significant loading times to your site.
One possibility could be to use geolocation based on client IP to determine what services are available but this has a number of disadvantages.:
- Geolocation based on IP is never perfect
- You need to maintain lists of locations and what services are available there - which may be subject to change
- This approach won't detect services that have been blocked by a company firewall.
For these reasons, dynamic service detection is recommended in preference to solutions based on geo-location.
SSW has created a simple Service Detection library for exactly this purpose called SSW Service Detector. This is open source and available from GitHub: SSW Service Detector.
This Service Detector works by attempting to download the Favicon.ico file from the website for each service you want to use. These favicon files are small, so if a service is available, the file will download very quickly. If a service is blocked, the connection could take a long time to timeout on its own. In this situation, the service detector uses a 1.5-second timer to attempt the download and will cancel the request after this time so that these connection attempts fail quickly and don't block the entire page.
- Figure Bad Example: Attempted requests to Facebook, Google, and Youtube from China took a long time to timeout, adding significant delays to the rendering of this page
- Figure: Good Example - Only 4 errors on F12 in China. Using SSW.ServiceDetector, there were only short, canceled requests raised to blocked services. The site was then able to fall-back gracefully for some services and load YouKu for videos