JS判断当前网络是否连接,执行对应逻辑
navigator.onLine、window.navigator.onLine只能判断当前是否连接网络(WiFi、4g、5g)不能判断当前链接的网络是否能上网
具体判断方法如下:
创建一张固定链接未百度的image,然后去访问它
var i = new Image();
// console.log(i);
i.src =
"https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo_top_ca79a146.png?t=" +
Date.parse(new Date());
// 设定超时事件,延迟 3000 毫秒
_this.netTimeout = setTimeout(function() {
// 超过2秒后 清除 onerror 和 onload 事件,并执行以下逻辑
i.onerror = i.onload = null;
_this.onLine = false;
//执行逻辑
_this.initMap();
_this.fenceGetFn();
// 执行无法加载的事件
}, 2200);
i.onload = function() {
//加载出来了就清除定时器
clearTimeout(_this.netTimeout);
_this.onLine = true;
_this.initMap();
_this.fenceGetFn();
};
i.onerror = function() {
//加载出来了就清除定时器
clearTimeout(_this.netTimeout);
//执行没网的逻辑
_this.onLine = false;
_this.initMap();
_this.fenceGetFn();
};
Comments | NOTHING