一种检测您的 JS 应用程序是否在线/离线/或连接速度慢的简单方法(+警报,+模拟慢速互联网)

2025-06-07

一种检测您的 JS 应用程序是否在线/离线/或连接速度慢的简单方法(+警报,+模拟慢速互联网)

在本文中,我们将介绍 3 件事:

  1. 如何检测您的 JS 应用程序(可以是 SPA、PWA、Electron 或纯 JS)是否存在连接问题(速度慢、离线)、何时恢复在线以及如何在不刷新页面的情况下重新下载数据(以防它在线时没有足够的时间完成)。

  2. 创建一个简单的 JS 应用程序来下载并显示图片,其中我们将涵盖上一步中的所有情况。

  3. 了解如何在 Chrome 中限制互联网连接,并测试我们创建的应用程序。


步骤1.

要检测应用程序是否离线或重新在线,非常简单:

window.addEventListener("offline", () => {
  console.log("I am offline.");
});

window.addEventListener("online", () => {
  console.log("I am back online.");
});

如果您正在构建需要互联网连接的 Chrome 扩展程序(例如将文件上传到 Google Drive),您可以利用以下方法:

if (!navigator.onLine) {
  return false;
}

// Upload the file...

要检测应用程序加载时间是否过长,可以创建一个计时器并设定一个时间。如果应用程序尚未加载,我们假设连接速度较慢。应用程序加载完成后,我们重置计时器。以下是示例代码:

// Our simple App
const App = async (onstart, onload) => {
  onstart();

  // Loading...

  // The application is now loaded
  onload();
}

let isSlow;
let loaded;

App(
  () => {
    isSlow = setTimeout(() => {
      console.log("Thing are getting slow...");
    }, 10000); // 10 seconds
  },
  () => {
    clearTimeout(isSlow);
    loaded = true;
    console.log("Loaded.");
});

我们判断应用程序是否加载时间过长的逻辑取决于我们的应用程序。

现在,我们可以进行下一步了。

第 2 步。

我们现在将创建一个简单的应用程序,它将从https://picsum.photos加载一张随机图片。如果网络连接变慢、离线或重新上线,我们将显示一条特定消息:

替代文本

替代文本

替代文本

该应用程序将如下所示:

替代文本

消息将在需要时显示在顶部中心。为了使图片加载时视觉效果更佳,我们将为其添加脉动效果。

让我们从创建开始index.html

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>App</title>
  <link rel="stylesheet" href="app.css">
</head>
<body>
  <div id="slow" class="message">Slow Internet Connection.</div>
  <div id="offline" class="message">No Internet Connection.</div>
  <div id="online" class="message">Back Online.</div>

  <div id="app"></div>

  <script src="app.js"></script>
</body>
</html>

继续创建app.css

body {
  margin: 0;
  padding: 4em;
  font-family: Arial, Helvetica, sans-serif;
}

@keyframes pulse {
  0% { background-color: #f1f1f1; }
  100% { background-color: silver; }
}

img {
  width: 640px;
  height: 480px;
}

img.loading {
  animation: pulse 1s ease-out alternate infinite;
}

.message {
  position: fixed;
  left: 50%;
  top: 0;
  font-size: 2em;
  font-weight: bold;
  padding: 1.5em;
  transform: translate(-50%, -100%);
  transition: transform .25s;
}

#slow {
  background: #FF9800;
  color: white;
}

#offline {
  background: #E91E63;
  color: white;
}

#online {
  background: #4CAF50;
  color: white;
}

body.slow #slow,
body.offline #offline,
body.online #online {
  transform: translate(-50%, 0);
}

每条消息(或提醒)都有不同的颜色,不需要时会隐藏在屏幕上。需要时,消息会从顶部中心滑入。

最后,创建app.js

// Simple App that loads a picture.
const App = (onstart, onload) => {
  onstart();

  const h1 = document.createElement("h1");
  h1.innerText = "App";

  const img = document.createElement("img");
  img.src = "https://picsum.photos/640/480";
  img.className = "loading";
  img.onload = () => {
    img.className = "";
    onload();
  };

  const app = document.getElementById("app");
  app.innerHTML = "";
  app.append(h1);
  app.append(img);
}

let isSlow;
let loaded;

const loadApp = () => {
  App(
    () => {
      loaded = false;
      isSlow = setTimeout(() => {
        // Show "Slow Internet Connection." message.
        document.body.className = "slow";
        console.debug("slow");
      }, 1500); // Intentionally a low number for testing. Try some different values here, or play with different Internet Throttling setting.
    },
    () => {
      loaded = true;
      clearTimeout(isSlow);
      setTimeout(() => { document.body.className = ""; }, 1000); // Hide message after 1s.
      console.debug("loaded");
  });
};


// We are "offline".
window.addEventListener("offline", () => {
  // Show "No Internet Connection." message.
  document.body.className = "offline";
});


// When we back "online".
window.addEventListener("online", () => {
  // Show "Back online" message.
  document.body.className = "online";
  console.debug("online");

  // Hide message after 1s.
  setTimeout(() => { document.body.className = ""; }, 1000);

  // There was not enough time to load the App. Do it again.
  if (!loaded) {
    console.debug("Reconnecting...");
    loadApp();
  }
});


window.addEventListener("DOMContentLoaded", loadApp);

这个简单的应用会加载并显示一张图片。在图片加载过程中,会.loading添加一个类,用于显示脉冲效果。图片加载完成后,该类.loading将被移除,计时器也会停止。如果加载时间超过我们指定的时间,Slow Internet Connection.则会显示一条消息。

如果互联网关闭,No Internet Connection.则会显示消息,一旦恢复在线,Back Online.也会显示消息。

如果在我们离线之前图片没有加载,那么当我们重新上线时它将再次加载。

步骤3.

是时候在不同的网络条件下测试我们的应用了。打开Chrome -> DevTools -> Network,找到Throttling部分,然后点击Add...

替代文本

替代文本

定义 2 个新的节流配置文件,如下所示:

替代文本

我们即将显示的随机图片大小可能在20KB80KB之间,这意味着,在“非常慢”配置下,加载时间约为 5 秒;在“极慢”配置下,加载时间约为 30 秒。我们基本上会根据内容大小调整加载速度,以便进行良好的测试。

现在,打开index.htmlDevTools (应用节流),使用不同的初始节流设置(在线离线非常慢非常慢)不断刷新页面并尝试在页面加载时更改配置文件(从离线在线;从非常慢离线在线;等等)。

它看起来像这样:

替代文本

就这样吧。希望你喜欢这篇文章,玩得开心!

还有。谢谢你的阅读! 🙂

文章来源:https://dev.to/penge/a-simple-way-to-detect-if-your-js-app-is-online-offline-or-having-a-slow-connection-alerts-emulated-the-slow-internet-1lb3
PREV
结合 Storybook、Cypress 和 Jest 代码覆盖率 代码覆盖率测试类型
NEXT
我用 HTML 和 CSS 构建了这 5 种类型的加载动画,您更喜欢哪一种?