“This is the third day of my participation in the First Challenge 2022. For details: First Challenge 2022”
preface
In real project, we for the sake of a good user experience, according to the user the status of the current network provides the best resources, such as images or video larger resources, such as when the network is poor, can provide resolution lower resources, can let the user see effective information as fast as possible, rather than always hang wait for.
Then how to design a production environment available small program current network status monitoring system. The following aspects are mainly considered:
- First of all, we can roughly use getNetworkType to obtain the current network connection type. When the type such as 2G or 3G is obtained, the current weak network state can be determined.
- When in 4g, 5G or wifi, our network will also have fluctuations, at this time we need to judge the network status according to the real network download situation.
- When the weak network is judged, we need to continuously obtain the current network condition. When the network condition improves or a maximum detection time is set, when the network still does not improve within the specified time, we will stop obtaining the network condition.
- The network status is transmitted through the global eventBus system for use by business functions.
implementation
Details of the steps
-
Delimit the judgment standard of the network, namely what situation is in weak network, when be in good network.
- 2g and 3G networks are considered as weak networks
- To actually get the current network request status by actually requesting an image, there are two ways:
- One is through the time, select a threshold range of 1000, 1500, below 1000 is the excellent network, the middle is the good network, more than 1500 is
- One is through the profile information provided in the request/ Download interface callbacks, where throughputKbps represents the actual downloaded KBPS for the current network.
-
Judge the treatment of weak network. Judgment after weak network, we can’t let our resources directly loading is a kind of weak network, the judgment after weak network, let us go to recursive continues to judge the network state, until the network better, or have a maximum retries, for a long time the network status is bad, need not trying to judge, users could not have been in this waiting for network better.
-
Continuous monitoring. That is, timing the network:
- One is to listen for a network type switch through wx.onNetworkStatusChange. When the network type is changed, determine the network
- Each time an interface requests, a network state judgment is made, so here we encapsulate a request method of our own, encapsulating the common logic in one place.
The code shown
// import eventBus from './eventBus';
const NETWORK_STATUS = {
OFFLINE: 'offline'.POOR: 'poor'.GOOD: 'good'.WONDERFUL: 'wonderful'
}
< 1000 indicates excellent network; between 1000 and 1500 indicates good network and above 1500 indicates weak network.
const DOWNLOAD_TIME = [1000.1500];
const MAX_COUNT = 10;
let count = 0;
function getNetworkType() {
return new Promise((resolve) = > {
wx.getNetworkType({
success(res) {
resolve(res);
},
fail(err){ resolve(err); }})})}const getNetworkStatus = (opt) = > {
return new Promise((resolve) = > {
try {
let networkType = opt && opt.networkType;
let networkStatus = NETWORK_STATUS.WONDERFUL;
if(! networkType) { networkType = getNetworkType().then(({networkType}) = > {
if (['unknown'.'none'].includes(networkType)) {
emitNetworkStatus(NETWORK_STATUS.OFFLINE);
return resolve(NETWORK_STATUS.OFFLINE);
}
if (['2g'.'3g'].includes(networkType)) {
emitNetworkStatus(NETWORK_STATUS.POOR);
return resolve(NETWORK_STATUS);
}
const startTime = +new Date(a); requestImage().then((result) = > {
const requestTime = +new Date() - startTime;
if (requestTime < DOWNLOAD_TIME[0]) {
networkStatus = NETWORK_STATUS.WONDERFUL;
} else if (requestTime > DOWNLOAD_TIME[1]) {
networkStatus = NETWORK_STATUS.POOR;
} else {
networkStatus = NETWORK_STATUS.GOOD;
}
emitNetworkStatus(networkStatus);
returnresolve(networkStatus); })}); }}catch(error) { resolve(NETWORK_STATUS.WONDERFUL); }})}function run() {
if (count >= MAX_COUNT) {
return;
}
const timer = setTimeout( () = > {
getNetworkStatus().then(networkStatus= > {
count += 1;
if([NETWORK_STATUS.POOR, NETWORK_STATUS.GOOD].includes(networkStatus)){ run(); }})clearTimeout(timer);
}, 5000)}function start(opt) {
const timer = setTimeout( () = > {
getNetworkStatus(opt).then(networkStatus= > {
if([NETWORK_STATUS.POOR, NETWORK_STATUS.GOOD].includes(networkStatus)) { run(); }})clearTimeout(timer);
}, 1000)}function requestImage() {
return new Promise((resolve) = > {
wx.request({
url: 'https://dss0.bdstatic.com/-0U0bnSm1A5BphGlnYG/tam-ogel/-146383143_-1016538910_80_80.png'.data: {
time: +new Date()},success(res) {
resolve(res);
},
fail() {
resolve()
}
})
})
}
function emitNetworkStatus(networkStatus) {
const app = getApp();
const oldNetwordStatus = app.globalData.networkStatus;
// Only the current status is inconsistent with that of the previous storage.
if(oldNetwordStatus ! == networkStatus) { app.globalData.networkStatus = networkStatus;// Send the result through the global event system
// eventBus.emit('networkChange', networkStatus, oldNetwordStatus); }}export const networkController = {
start,
};
Copy the code
The eventBus functionality can be wrapped in its own project, which I won’t cover here.
Call time
- On the onLaunch hook in app.js, listen for wx.onNetworkStatusChange. Where we call our method
wx.onNetworkStatusChange((res) = > {
networkController.start(res);
})
Copy the code
- The other option is to call the interface once each time we request it in our wrapped Request function. In this way, we can ensure that we can not frequently but effectively judge whether to judge the current network state
conclusion
As a C – end product, the optimization of weak network is essential. User experience issues should always be at the forefront, and as a developer you should always pay attention to these points so as not to create a bad user experience.
If there is a better opinion, hard comment section pointed out, learn together, improve together.