How to deal with the disconnection of browser?
Zhang Zhiqiang 2020-11-27 11:04:48
author : While you are young source :segmentfault

 How to deal with the disconnection of the browser ?


Good disconnection will be very comfortable :lol It's broken and reconnected , The broken line and reconnection of the king's glory To ensure that the game continues

If the network is broken or not handled, it will come out bug: For example, I have a project in hand bug The business people said they were very upset

The network problem has always been a problem worthy of attention .

For example, in the case of slow network , increase loading Avoid repeating requests , Use promise The return result of the request is processed sequentially , Or add some friendly upload progress tips and so on .

So, have you ever thought about what to do when you are disconnected ? For example, the network is normal -> Broken net -> Normal network .

Actually, I never thought about , Until a test in the group detects a disconnection bug, Let me realize that I'm heavily dependent on the front end of network requests , In the case of disconnection, serious bug.

Therefore, I will record my own handling of the system disconnection , On the one hand, avoid bug produce , On the one hand, it ensures that users know that the network has been disconnected in the application

overview

  • Used to detect whether the browser is connected to the Internet navigator.onLine
  • Used to detect network conditions navigator.connection
  • Disconnection event "offline" And networking "online"
  • The actual operation of network disconnection processing project
    • Ideas and effects
    • The disconnection processing component uses
    • Details of disconnection processing components
    • Find out
  • Reference material

overview

To build a “ Broken net (offline) You can use ” Of web application , You need to know when the app is disconnected (offline) Of .

It's not just about knowing when to disconnect , We need to know when the network will return to normal (online).

It can be broken down into the following two common situations :

  1. You need to know when users online, So that you can talk to the server re-sync( To resynchronize ).
  2. You need to know when users offline, In this way, you can send requests that you haven't sent out to the server after a period of time .

Usually it can be done by online/offline Events to do this .

Used to detect whether the browser is connected to the Internet navigator.onLine

navigator.onLine

  • true online
  • false offline

Can pass network Of online The option switches to offline, Print navigator.onLine verification .

When the browser cannot connect to the network , This property will update . It's defined in the specification :

The navigator.onLine attribute must return false if the user agent will not contact the network when the user follows links or when a script requests a remote page (or knows that such an attempt would fail)...

Used to detect network conditions navigator.connection

stay youtube When watching the video , Automatic detection of network conditions, how to achieve switching clarity ?

Domestic video website will also give a switch network reminder , How to detect it ?

in other words , Is there any way to detect network conditions ? Judge whether the current network is fluent , Traffic jam , Busy ?

Can pass navigator.connection, Properties include effectiveType,rtt,downlink And changing network events change. Inherited from NetworkInformation API.

navigator.connection

online Running in state console.log(navigator.connection);


{

onchange: null,

effectiveType: "4g",

rtt: 50,

downlink: 2,

saveData: false

}

adopt navigator.connection It can be judged online,fast 3g,slow 3g, and offline, In these four states effectiveType Respectively 4g,3g,2g,4g(rtt,downlink Are all 0).

rtt and downlink What is it? ?NetworkInformation What is it? ?

These are two parameters that reflect the state of the network , Than type More concrete and more able to reflect the real situation of the current network .

Common network conditions rtt and downlink surface


 How to deal with the disconnection of the browser ?


Be careful :rtt and downlink Not fixed value , It's real-time .online when , Maybe it's now rtt 100ms,2.2Mb/s, The next second it will be 125ms,2.1Mb/s 了 .

rtt

  • Connection estimated round trip time
  • Unit is ms
  • The value is rounded to 25 The closest multiple of milliseconds ( That is to say, this value x%25===0, Can observe the common network situation rtt and downlink surface )
  • The smaller the value, the faster the network speed . similar ping Of time Well
  • stay Web Worker Available in the

downlink

  • Estimated bandwidth
  • Unit is Mbit/s( Note that Mbit, No MByte.)
  • The value is also rounded to the nearest 25 The bit / Multiple of seconds ( That is to say, this value x%25===0, Can observe the common network situation rtt and downlink surface )
  • Generally, the wider the width, the faster the speed , That is to say , More can be transmitted over the channel .( Poking fun at a , The communication principles I've learned are quite useful .)
  • The higher the value, the faster the network speed . Similar to the highway, it is generally wider than the national highway .
  • stay Web Worker Available in the

The draft (Draft) Stage NetworkInformation API

Whether it's rtt, still downlink, It's all from this draft .

In addition to that downlinkMax,saveData,type Equal attribute .

More information can be found in :NetworkInformation

How to detect network changes to respond ?

NetworkInformation Inherited from EventTarget, By monitoring change Events to make some response .

For example, changes in network conditions can be obtained ?


var connection = navigator.connection;

var type = connection.effectiveType;

function updateConnectionStatus() {

console.log(" The state of the Internet has changed from " + type + " Switch to " + connection.effectiveType);

type = connection.effectiveType;

}

connection.addEventListener('change', updateConnectionStatus);

After listening changes , We can play one Modal Remind users , You can also come up with a Notice Inform users of network changes , Or more advanced to automatically switch clarity ( This should be more difficult ).

extraction NetworkInformation The concept of , It's just a function of throwing a brick to attract jade . This fine-grained network condition detection , Can be combined with specific needs to achieve .

In this post , We only deal with disconnection and interconnection , Let's take a look at the disconnection event "offline" And networking "online".

Disconnection event "offline" And networking "online"

The browser has two events :"online" and "offline".

These two events will be in the browser in online mode and offline mode When switching between , By the page's <body> Launch out .

Events will bubble in the following order :document.body -> document -> window.

Events can't be cancelled ( Developers can't manually change code to online perhaps offline, Using developer tools during development can ).

Several ways to register online and offline events

The best advice is window+addEventListener The combination of .

  • adopt window or document or document.body and addEventListener(Chrome80 only window It works )
  • by document or document.body Of .ononline or .onoffline Property to set a js function .( Be careful , Use window.ononline and window.onoffline There will be compatibility issues )
  • You can also register events through tags <body ononline="onlineCb" onoffline="offlineCb"></body>

Example


 How to deal with the disconnection of the browser ?


 How to deal with the disconnection of the browser ?


<div id="status"></div>

<div id="log"></div>

window.addEventListener('load', function() {

var status = document.getElementById("status");

var log = document.getElementById("log");

function updateOnlineStatus(event) {

var condition = navigator.onLine ? "online" : "offline";

status.innerHTML = condition.toUpperCase();

log.insertAdjacentHTML("beforeend", "Event: " + event.type + "; Status: " + condition);

}

window.addEventListener('online', updateOnlineStatus);

window.addEventListener('offline', updateOnlineStatus);

});

among insertAdjacentHTML Is to insert... Near the label node , You can refer to :DOM Advanced insertAdjacentHTML

The actual operation of network disconnection processing project

be based on vue as well as iView Of Spin,Notice Components encapsulate offline processing components , In the page that needs to be introduced .

Ideas and effects

As long as the network is disconnected + Mask , Online reminder - Mask it .

  • monitor offline, Disconnection gives reminders and masks : The network has been disconnected , Please check the network connection .
  • monitor online, Networking gives reminders and masks : The network is connected .

 How to deal with the disconnection of the browser ?

The disconnection processing component uses


<OfflineHandle

:offlineTitle = " Disconnection processing title "

:desc=" Description of disconnection processing "

:onlineTitle=" Internet alert "

>

</OfflineHandle>

Details of disconnection processing components


<!--OfflineHandle.vue-->

<template>

<div v-if="spin" class="offline-mark">

<Spin size="large" fix>

<h2>{{offlineTitle}}</h2>

<p>{{desc}}</p>

</Spin>

</div>

</template>

<script>

export default {

name: 'offline-handle',

props: {

offlineTitle: {

type: String,

default: ' The network has been disconnected , Please check the network connection .',

},

onlineTitle: {

type: String,

default: ' The network is connected ',

},

desc: {

type: String,

default: '',

},

duration: {

type: Number,

default: 4.5,

},

},

data() {

return {

spin: false,

};

},

mounted() {

window.addEventListener('offline', this.eventHandle);

window.addEventListener('online', this.eventHandle);

},

beforeDestroy() {

window.removeEventListener('offline', this.eventHandle);

window.removeEventListener('online', this.eventHandle);

},

methods: {

eventHandle(event) {

const type = event.type === 'offline' ? 'error' : 'success';

this.$Notice[type]({

title: type === 'error' ? this.offlineTitle : this.onlineTitle,

desc: type === 'error' ? this.desc : '',

duration: this.duration,

});

setTimeout(() => {

this.spin = event.type === 'offline';

}, 1500);

},

},

};

</script>

<style lang="scss" scoped>

.offline-mark {

position: fixed;

top: 0;

left: 0;

right: 0;

bottom: 0;

background-color: #ccc;

z-index: 9999;

transition: position 2s;

}

/deep/.ivu-spin-fix {

text-align: left;

font-size: 20px;

h2 {

color: rgba(0, 0, 0, 0.8);

}

p {

margin-top: 20px;

color: red;

font-weight: bold;

}

}

</style>

Find out

  • offline and online event :window It works ,document and document.body Invalid settings

The project in hand only runs on Chrome browser , Only for window Set up offline and online To take effect .

Running environment :"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36

版权声明
本文为[Zhang Zhiqiang]所创,转载请带上原文链接,感谢
https://fheadline.com/2020/11/20201127110231755v.html
相似文章

2021-08-09