【JS 】SharedWorker 优化前端轮询请求

1. 背景

目前公司系统首页存在一个定时的轮询请求/Admin/Dashboard/GetAppRelaseNotice,包含一些需要实时反映在前端的操作(如:页面版本,站内信,页面配置更新等)

问题很明显,单个页面的情况下,每分钟会发送一次请求;
但如果同时打开多个tab,每个tab每分钟都会发送一次请求

2. 思路

针对这个情况,可以使用 SharedWorker + BroadcastChannel 来实现多个tab共用一个后台任务的情况,减少后端服务器压力的同时也可以提升部分前端的性能;

SharedWorker接口代表一种特定类型的 worker,可以从几个浏览上下文中访问。
BroadcastChannel接口代理了一个命名频道。它允许同源的不同浏览器窗口下的不同文档之间相互通信。

  1. 使用SharedWorker将请求任务移至后台轮询,多页面共享
  2. 通过BroadcastChannel通知所有页面请求结果
  3. 兼容不支持 SharedWorker 的浏览器

3. 编码

3.1 使用SharedWorker将请求任务移至后台轮询,多页面共

建立一个后台任务js文件 GetAppRelaseNotice.js

onconnect = function (e) {
    checkAppReleaseCallBack();
    setInterval(checkAppReleaseCallBack, 1000 * 1);  //先设置1秒钟,用于测试
}

function checkAppReleaseCallBack() {
    // 这里请求 GetAppRelaseNotice 接口获取返回值
}

页面启动后台任务

function startCheckAppRelease() {
    // 给后台任务一个名字 GetAppRelaseNotice 后面用于调试
    const worker = new SharedWorker('/Scripts/Workers/GetAppRelaseNotice.js', "GetAppRelaseNotice");
    worker.port.start();
}

3.2 通过BroadcastChannel通知所有页面请求结果

// 后台任务js
const broadcast = new BroadcastChannel('LinkMore:GetAppRelaseNotice');
broadcast.postMessage(data); //发送广播数据

// 页面js,订阅广播
const broadcast = new BroadcastChannel('LinkMore:GetAppRelaseNotice');
broadcast.onmessage = (msg) => {
    const data = msg.data; // 获取广播数据
};

3.3 兼容不支持 SharedWorker 的浏览器

// 检测应用发版通知
function startCheckAppRelease() {
    if (typeof window.SharedWorker === "undefined") { // 如果不存在则沿用老的逻辑
        checkAppReleaseCallBack();
        setInterval(checkAppReleaseCallBack, 1000 * 60);
    } else {
        // 这里处理 SharedWorker
    }
}

4. 完整代码

GetAppRelaseNotice.js

let timer;
onconnect = function (e) {
    checkAppReleaseCallBack();
    clearInterval(timer);
    timer = setInterval(checkAppReleaseCallBack, 1000 * 60);
}
// 创建广播对象
const broadcast = new BroadcastChannel('LinkMore:GetAppRelaseNotice');
function checkAppReleaseCallBack() {
    fetch("/Admin/Dashboard/GetAppRelaseNotice", { method: "POST" })
        .then(r => r.text())
        .then(JSON.parse)
        .then(r => broadcast.postMessage(r));
}

页面代码


function startCheckAppRelease() {
    if (typeof window.SharedWorker === "undefined") {
        checkAppReleaseCallBack();
        setInterval(checkAppReleaseCallBack, 1000 * 60);
    } else {
        const worker = new SharedWorker('/Scripts/Workers/GetAppRelaseNotice.js', "GetAppRelaseNotice");
        worker.port.start();
        // 订阅广播消息
        const broadcast = new BroadcastChannel('LinkMore:GetAppRelaseNotice');
        broadcast.onmessage = msg => {
            const rst = msg.data; // 获取广播数据
            doAppReleaseCallBack(rst);
        };
    }
}

function checkAppReleaseCallBack() {
    $.post("/Admin/Dashboard/GetAppRelaseNotice", function (rst) {
        checkAppReleaseCallBack(rst);
    })
}

function doAppReleaseCallBack(rst) {
    // 业务逻辑不变
    if (rst.result == 0 && rst.data != "" && rst.data != null) {
        document.querySelector("#ReleaseNotice").stop();
        $("#ReleaseNotice").show();
        $("#ReleaseNotice").html(rst.data);
        document.querySelector("#ReleaseNotice").start();
    } else {
        $("#ReleaseNotice").hide();
    }
}

5. 调试

浏览器输入:chrome://inspect

多个页面都可以收到消息,但后台任务只发一次请求

所有页面关闭后任务会自动停止

posted @ 2023-02-19 00:55  冰麟轻武  阅读(210)  评论(0编辑  收藏  举报