Original address juejin.cn/post/695386… Good disconnection processing will make people very comfortable: LOL disconnection re-connection, King of Glory disconnection re-connection can ensure that the game continues to carry on bad disconnection processing or even not dealing with the bug: for example, I have a bug on the project business staff expressed very distressed network problems has been a very worthy of attention. For example, in the case of slow network, loading should be added to avoid repeating requests, promise should be used to process the return results of requests in sequence, or some friendly hints of uploading progress should be added. So have you ever thought about what to do when you’re offline? For example, the network is normal -> Disconnected -> The network is normal. In fact, I never thought about it until a test in the group detected a bug caused by disconnection of the network, which made me realize that the front-end, which relies heavily on network requests, may have serious bugs in the case of disconnection of the network. Therefore, I will record my treatment of system disconnection here, on the one hand, to avoid bugs, on the other hand, to ensure that users know in the application that the network has been disconnected

OnLine Navigator. Connection disconnection event “OFFLINE” and network disconnection event “onLine” used for checking network status

The network disconnection processing component is discovered using the details of the network disconnection processing component

The resources

In order to make a Web application offline, you need to know when the application is offline. Not only do you need to know when to go offline, but you need to know when to get your Internet back online. The following two common situations can be broken down:

You need to know when the user is online so you can re-sync with the server. You need to know when a user is offline, so you can send unsent requests to the server for a while.

You can usually do this with an online/offline event. Navigator.online Navigator.online, which is used to check whether the browser is connected to the Internet

true online false offline

You can switch network online to Offline and print navigator. online verification. This property is updated when the browser cannot connect to the network. The specification defines it as follows:

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)…

How does navigator.Connection automatically detect network health switch sharpness when watching videos on YouTube? The video website of home also can give the reminder that switches a network, how should detect? In other words, is there a way to detect network health? Is the current network smooth, congested or busy? Navigator. connection. Properties include effectiveType, RTT, downLink and change network event change. Inheriting from NetworkInformation API. Run console.log(navigator. Connection) when navigator.connection is online; { onchange: null, effectiveType: “4g”, rtt: 50, downlink: 2, saveData: False} The effectiveType values of online, fast 3G, slow 3G, and offline are 4G, 3G, 2G, 4g (RTT, Downlink is 0). What are RTT and downlink? What is NetworkInformation? These are two parameters that reflect the network condition. They are more specific than Type and can better reflect the current network condition. RTT and downlink table for common network conditions

Network status RTT (ms) DownLink (Mbit/s)online1002.2 Fast 3G6001.55Slow 3G21500.4offline00 Note: RTT and downlink are not fixed values but change in real time. When online, it might be RTT 100ms, 2.2MB /s now, and 125ms, 2.1MB /s the next second. rtt

Connection estimated round-trip time in ms values are rounded to the nearest multiple of 25 milliseconds (that is, this value x%25===0, you can observe common network conditions RTT and downlink table) the lower the value the faster the network speed. Ping-like time bars are available in Web workers

downlink

The estimated bandwidth is in Mbit/s, not In MByte. The value is also rounded to the nearest multiple of 25 bits/SEC (that is, x%25=== =0, as you can see in the RTT and downlink tables). Generally, the wider the channel, the faster the speed, i.e., the more transmission can be carried on the channel. (Just kidding, the communication principles learned are quite useful.) The higher the value, the faster the network speed. Similar highways are generally wider than national highways. Available in Web Workers

Both RTT and DownLink are part of the Draft NetworkInformation API. In addition, there are downlinkMax, saveData, Type and other attributes. How does NetworkInformation detect network changes and respond to them? NetworkInformation inherits from EventTarget and can listen for the change event to do something in response. For example, can you get changes in network health? Var connection = navigator.connection; var type = connection.effectiveType;

Function updateConnectionStatus() {console.log(” Network status changed from “+ type +” to “+ connection.effectiveType); type = connection.effectiveType; }

connection.addEventListener(‘change’, updateConnectionStatus); After copying the code to listen for changes, we can play a Modal alert to the user, issue a Notice to notify the user of network changes, or we can go to a higher level to automatically switch sharpness (this should be more difficult). Leading to the concept of NetworkInformation, just think of a role. Such fine – grained network condition detection can be implemented according to specific requirements. In this blog post, we will only deal with two cases of disconnection and network connection. The following are the disconnection events “offline” and the network connection events “online”. Offline event “Offline” and Connection event “Online” The browser has two events: “Online” and “Offline “. These two events are emitted by the page when the browser switches between Online mode and Offline mode. Events bubble in the following order: document.body -> document -> window. Events cannot be cancelled (developers cannot manually make them online or offline in code, using developer tools during development). A combination of Window and addEventListener is the most recommended way to register up and down events.

Through window or document or document.body and addEventListener(Chrome80 only window valid) Set a js function for the.onOnline or.onOffline property of document or document.body. (Note that window.ononline and window.onoffline have compatibility issues.) Events can also be registered via tags

example

function updateOnlineStatus(event) { var condition = navigator.onLine ? “online” : “offline”; status.innerHTML = condition.toUpperCase();

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

}

window.addEventListener(‘online’, updateOnlineStatus); window.addEventListener(‘offline’, updateOnlineStatus); }); DOM advanced insertAdjacentHTML processing projects can use vUE and React to package offline processing components and introduce them into pages that need to be used. Train of thought and effect as long as do disconnection remind + mask, line remind – mask can be.

The network has been disconnected. Please check the network connection. Listen online to give an alert and mask: the network is connected.

Codesandbox. IO /s/offline-h…

IO /s/offline-h… // offlineHandle.js import React, { useState, useEffect } from “react”; import { notification } from “antd”; import “antd/dist/antd.css”; import “./index.css”;

Const OfflineHandle = (props) => {const {offlineTitle = “The network is disconnected, please check the network connection.” , onlineTitle = “network connected “, desc, duration = 4.5} = props; const [mask, setMask] = useState(false);

const eventHandler = (event) => { const type = event.type === “offline” ? “error” : “success”; console.log(desc, “desc”); openNotification({ type, title: type === “error” ? offlineTitle : onlineTitle, desc: type === “error” ? desc : “”, duration }); setTimeout(() => { setMask(event.type === “offline”); }, 1500); };

const openNotification = ({ type, title, desc, duration }) => { notification[type]({ message: title, description: desc, duration }); };

useEffect(() => { window.addEventListener(“offline”, eventHandler); window.addEventListener(“online”, eventHandler); return () => { window.removeEventListener(“offline”, eventHandler); window.removeEventListener(“online”, eventHandler); }; } []);

const renderOfflineMask = () => { if (! mask) return null; return (

{offlineTitle}

    <p className="offline-mask-desc">{desc}</p >
  </div>
);
Copy the code

};

return <>{renderOfflineMask()}</>; };

export default OfflineHandle; Copy the code index. CSS file to vue’s style tag. found

Offline and Online events: Window is valid, document and document.body Settings are invalid

The project in hand only runs in Chrome, and only works if you set Offline and Online for Windows. Run 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

Add transition to Position for 2s to avoid screen flicker

References:

Developer.mozilla.org/en-US/docs/… Developer.mozilla.org/en-US/docs/… Developer.mozilla.org/en-US/docs/… Developer.mozilla.org/en-US/docs/…

By: Doodle big front end link: juejin.cn/post/695386… The copyright belongs to the author. Commercial reprint please contact the author for authorization, non-commercial reprint please indicate the source.