前端性能优化:使用 Web Workers 实现轮询
// pollWorker.js
import { Base64 } from 'js-base64';
import RsaAndAes from '~/composables/RsaAndAes';
import { getRandomNumberFn } from '~/composables/baseRequest';
export function createWorker() {
const blob = new Blob(
[
`
let requestCount = 0;
// 处理收到的消息
self.onmessage = function (event) {
if (event.data.type === "start") {
// 开始轮询
const interval = event.data.interval;
startPolling(interval, event.data.url, event.data.data, event.data.headers);
}
};
// 开始轮询函数
function startPolling(interval, url, data, headers) {
function poll() {
fetch(url, {
method: "POST",
headers: new Headers(headers),
body: JSON.stringify({ ...data }),
})
.then((response) => {
return response.json();
})
.then((res) => {
// 将请求结果发送回主线程
self.postMessage({ res, requestCount: requestCount++ });
})
.catch((error) => {
console.log("Request failed:", error);
});
// 调用自身以实现持续轮询
setTimeout(poll, interval);
}
// 立即执行一次
poll();
}
`
],
{ type: 'application/javascript' }
);
const worker = new Worker(URL.createObjectURL(blob));
// 将post函数传递给WebWorker
const TOKEN = '';
const saveData = JSON.parse(JSON.stringify({} || {}));
const config = {};
const interDomainName = '';
const ENV = '';
const nodeEnv = '';
const Key = ''; //存储公钥
// 发送开始消息给WebWorker,传递轮询间隔
worker.postMessage({
type: 'start',
interval: 5000,
url: 'http://192.168.110.145:18200/gateway/xxxxxxx',
headers: {
'content-type': 'application/json; charset=utf-8',
partnerId: 'MTAy',
time: '',
accountId: '',
countries: '',
authToken: TOKEN,
requestId: ''
},
data: {
secretCode: RsaAndAes.encrypt(Key),
encryptedData: RsaAndAes.encryptAes(saveData)
}
}); // 每5秒轮询一次
return worker;
}
异乡小龟