Good disconnection handling is comfortable: LOL disconnection and reconnection, King of Glory disconnection and reconnection will keep the game going

Bad disconnection processing or even no processing will give a bug: for example, the project on my hand out a bug business personnel expressed very distressed

Network problem has always been a problem worth paying attention to.

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

  • An overview of
  • Navigator. onLine, used to check whether the browser is connected to the Internet
  • Navigator.connection to detect network health
  • Offline event and Online Event
  • Off-network processing project actual combat
    • Ideas and Effects
    • Use the disconnection processing component
    • Details about the disconnection processing component
    • found
  • The resources

An overview of

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:

  1. You need to know when the user is online so you can re-sync with the server.
  2. 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, used to check whether the browser is connected to the Internet

navigator.onLine

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

Navigator.connection to detect network health

How is it possible to automatically detect network conditions and switch sharpness while 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.

navigator.connection

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

{
    onchange: null,
    effectiveType: "4g",
    rtt: 50,
    downlink: 2,
    saveData: false
}
Copy the code

Navigator. connection indicates that online, fast 3G, slow 3G, and Offline effectiveType are 4G, 3G, 2G, and 4G respectively (RTT and downlink are 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

The network status rtt(ms) downlink(Mbit/s)
online 100 2.2
fast 3g 600 1.55
slow 3g 2150 0.4
offline 0 0

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
  • The unit is ms
  • The value is rounded to the nearest multiple of 25 milliseconds (i.e. X %25=== =0). You can observe common network conditions in RTT and downlink tables.
  • The lower the value, the faster the network speed. Time like ping
  • Available in Web Workers
downlink
  • Bandwidth estimation
  • The unit is Mbit/s (Note that it is Mbit, not MByte).
  • The value is also rounded to the nearest multiple of 25 bits/SEC (i.e. X %25=== =0).
  • Generally, the wider the channel, the faster the speed, that is, the more you can carry 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
The Draft NetworkInformation API

Both RTT and downlink are included in this draft. In addition, there are downlinkMax, saveData, Type and other attributes. More information can be found at NetworkInformation

How do you detect network changes to 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?

varThe connection = the navigator. Connection;var type = connection.effectiveType;

function updateConnectionStatus() {
  console.log("Network condition from" + type + "Switch to" + connection.effectiveType);
  type = connection.effectiveType;
}

connection.addEventListener('change', updateConnectionStatus);
Copy the code

After monitoring changes, we can play a Modal to remind users, or issue a Notice to notify users of network changes, or we can go to a more advanced level to automatically switch the definition (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 and Online Event

Browsers have two events: “online” and “offline”. These two events are emitted by the of 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).

Several ways to register online and offline events

The most recommended combination is window+addEventListener.

  • 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.)
  • You can also register events with tags<body ononline="onlineCb" onoffline="offlineCb"></body>

example

<div id="status"></div>
<div id="log"></div>
Copy the code
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);
});
Copy the code

InsertAdjacentHTML inserts adjacent to the tag nodes. See DOM Advanced insertAdjacentHTML

Off-network processing project actual combat

You can use VUE and React to encapsulate offline processing components and import them on the required page.

Ideas and Effects

As long as do off network remind + mask, online 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.

Use the disconnection processing component

<OfflineHandle
    offlineTitle = "Disconnection Handling title"
    desc="Description of Disconnection Treatment"
    onlineTitle="Network Alert"
/>
Copy the code
Vue components

Codesandbox. IO /s/offline-h…

<! --OfflineHandle.vue-->
<template>
  <div v-if="mask" class="offline-mask">
    <h2 class="offline-mask-title">{{ offlineTitle }}</h2>

    <p class="offline-mask-desc">{{ desc }}</p>
  </div>
</template>

<script>
export default {
  name: "offline-handle".props: {
    offlineTitle: {
      type: String.default: "The network is disconnected. Please check the network connection.",},onlineTitle: {
      type: String.default: "Network connected",},desc: {
      type: String.default: "",},duration: {
      type: Number.default: 4.5,}},data() {
    return {
      mask: false}; },mounted() {
    window.addEventListener("offline".this.eventHandle);
    window.addEventListener("online".this.eventHandle);
    console.log(this.desc);
  },
  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.mask = event.type === "offline";
      }, 1500); ,}}};</script>

<style lang="css" scoped>
.offline-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ccc;
  z-index: 9999;
  transition: position 2s;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
}
.offline-mask-title {
  color: rgba(0.0.0.0.8);
}
.offline-mask-desc {
  margin-top: 20px;
  color: red;
  font-weight: bold;
}
</style>
Copy the code
The React components

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 (
      <div className="offline-mask">
        <h2 className="offline-mask-title">{offlineTitle}</h2>

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

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

export default OfflineHandle;
Copy the code

The index. CSS file is the same as the vue 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/…

I look forward to communicating with you and making progress together

  • SegmentFault column: Be a good front-end engineer while you’re still young
  • excellent_developers

Strive to be an excellent front-end engineer!