-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathindex.html
68 lines (65 loc) · 2.27 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1, user-scalable=0, minimal-ui=yes" charset="UTF-8">
<title>移动端网络连接判断</title>
<script>
;(function(win){
var wifi = true;
var ua = win.navigator.userAgent;
var con = win.navigator.connection;
// 如果是微信
if(/MicroMessenger/.test(ua)){
// 如果是微信6.0以上版本,用UA来判断
if(/NetType/.test(ua)){
var result = ua.match(/NetType\/(\S)+/)[0].replace('NetType/','');
if(result && result != 'WIFI'){
wifi = false;
}
// 如果是微信6.0以下版本,调用微信私有接口WeixinJSBridge
}else{
document.addEventListener("WeixinJSBridgeReady",function onBridgeReady(){
WeixinJSBridge.invoke('getNetworkType',{},function(e){
if(e.err_msg != "network_type:wifi"){
wifi = false;
}
});
});
}
// 如果支持navigator.connection
}else if(con){
var network = con.type;
if(network != "wifi" && network != "2" && network != "unknown"){ // unknown是为了兼容Chrome Canary
wifi = false;
}
}
win.networkWIFI = wifi;
})(window);
</script>
</head>
<body>
<img id="pic" src="data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=" data-src="images/100x100.png" data-src2="images/200x200.png" data-src3="images/300x300.png" alt="" width="100" height="100">
<p>利用网络连接判断如果是WIFI加载高清图片</p>
<script>
window.onload = function(){
var $img = document.querySelector("#pic");
var dpr = window.devicePixelRatio || 1;
// 替换图片
if(networkWIFI){
if(dpr >= 3){
$img.setAttribute('srcset', $img.getAttribute('data-src2')+" 2x,"+$img.getAttribute('data-src3')+" 3x");
$img.setAttribute('src', $img.getAttribute('data-src2'));
}else{
$img.setAttribute('src',$img.getAttribute('data-src2'));
}
}else{
if(dpr >= 3){
$img.setAttribute('src',$img.getAttribute('data-src2'));
}else{
$img.setAttribute('src',$img.getAttribute('data-src'));
}
}
};
</script>
</body>
</html>