The implementation code that determines the networking type and connection status through JS

  • 2020-05-24 05:13:28
  • OfStack

China's mobile network environment is complex, in order to bring users better access experience, developers hope to understand the user's current networking mode, and then give users a result of a request in line with the current network environment.

The W3C specification provides a way to obtain the current network state. According to the protocol specification of Working Draft 29 November 2012, we can obtain the values of bandwidth (bandwidth, M/s) and metered from the interface. It also provides a listening method to monitor the changes in the access environment. Reality we found many browsers do not return bandwidth value, and abide by the Working Draft 07 June 2011 is returned to the agreement of our type (type, wifi g / 2/3 g / 4 g).

Let's look at the level of support

Android 2.3+ Browser UC Dolphin QQ浏览器 Baidu Firefox Chrome Opera Mini Maxthon
Yes No* Yes Yes* Yes Yes(New) No No Yes

Note that this information is not available to any browser in iPhone.

Through the above explanation, we find that we can understand the networking situation of a large part of users through this parameter, and provide them with a better experience.
Let's focus on the return of each browser.

Most browsers return an int type, with the exception of the QQ browser, which returns the type name, as shown below

返回值 QQ返回值 类型
0 unknown UNKNOWN
1 ethernet ETHERNET
2 wifi WIFI
3 2g CELL_2G
4 3g CELL_3G
5 4g CELL_4G(中国现在也会出现这个值,是hspa+)
? none NONE

Next comes a larger exception, firefox, which USES the new specification, so it returns bandwidth; But the odd thing is that if it's wifi or 3G he returns 20, if it's 2G he returns 0.1953125; One at a time no matter what the network state is. This issue will continue to follow.

Give everyone a demo address: http: / / demo ofstack. com/js / 2015 / net html
Demo directly returns {type:0} to browsers that do not support connection, which is a convenient way to solve some problems that browsers do not support. It makes sense, of course, to handle "unknown" for an unsupported web browser.

Many engineers think that this function is not good support, or not to use the good; But I think as long as the mistakes can be handled and the risks can be contained, why not offer a friendlier experience to those customers who are inherently superior.

Today we talked about letting the back end judge the speed, which might be a little bit difficult; However, it is possible to get the user's approximate speed with each asynchronous request (the loading time and file size can be obtained at the front end), then offer some optional services, and then prepare to think more in this direction.


Related articles: