优化点:
1. 防抖
// 当观察到变动时执行的回调函数
const callback = debounce(mutationsList => {
if (!this.lifeCycle.disposed && document.visibilityState === 'visible') {
this.registerVSLComponent();
}
}, 1500);
2. 删除重复语音指令
// 删除重复语音
searchVoiceConfig(ele) {
let configs = [];
if (ele.children && ele.children.length) {
Array.from(ele.children).forEach((element, index) => {
let config = [],
repeatKey = '';
if (element.data && element.data.raw.voiceType) {
const index = element.data.get('voiceIndex');
const item = {
id: element.id,
type: element.data.raw.voiceType,
autolisten: element.data.raw.voiceAutolisten,
resourceID: element.data.raw.voiceResourceID || '',
data: {
name: element.data.raw.voiceTag,
type: element.data.raw.voiceName || ''
},
indexinfo: /^([1-9]{1}[0-9]*)|0$/.test(index) ? {index} : {}
};
if (item.type === 'scroll-vertical') {
item.type = 'scroll';
item.data.type = 'vertical';
} else if (item.type === 'scroll-horizontal') {
item.type = 'scroll';
item.data.type = 'horizontal';
}
config = [item];
this._actionEleMap[element.id] = element;
repeatKey = item.data.name + item.type + item.indexinfo.index || '' + item.data.type;
}
if (repeatKey && !this._repeatMap[repeatKey]) {
this._repeatMap[repeatKey] = true;
configs = configs.concat(config, this.searchVoiceConfig(element) || []);
} else {
configs = configs.concat([], this.searchVoiceConfig(element) || []);
}
});
}
return configs;
}
3. 通过async await保证注册前先执行反注册
/**
* 注册 vsl 内容
*/
async registerVSLComponent() {
// 把旧的反注册
await this.unregisterVSLComponent();
// ......
},
/**
*
* 反注册 vsl 内容
*/
unregisterVSLComponent() {
return new Promise((res, rej) => {
try {
this.boxjsHandler('unRegister', this._vslActionQueue);
this._vslActionQueue = [];
this._actionEleMap = {};
res();
} catch (error) {
rej();
}
});
},
4. 判断当前要注册的内容与上次是否相同
JSON.stringify(configs) != JSON.stringify(curr_vslActionQueue)
5. 缓存注册了指令的节点,语音命中后从缓存里取
this._actionEleMap[element.id] = element;
const element = this._actionEleMap[voicedata.id];
6. 优化监听节点的策略
childList: true, // 观察目标子节点的变化,是否有添加或者删除
attributes: false, // 观察属性变动
subtree: true // 观察后代节点,默认为 false
7. 通过借鉴pwa的 ServiceWorker线程
通过postMessage与Render线程提供通信能力,遍历的事情交给ServiceWorker
const makeWorker = f => {
let pendingJobs = {};
const worker = new Worker (
URL.createObjectURL (new Blob ([`(${f.toString ()})()`]))
);
worker.onmessage = ({data: {result, jobId}}) => {
// 调用resolve,改变Promise状态
pendingJobs[jobId] (result);
// 删掉,防止key冲突
delete pendingJobs[jobId];
};
return (...message) =>
new Promise (resolve => {
const jobId = String (Math.random ());
pendingJobs[jobId] = resolve;
worker.postMessage ({jobId, message});
});
};
function work () {
onmessage = ({data: {jobId, message}}) => {
console.log ('work单独处理数据:-----' + message);
//处理操作
postMessage ({jobId, result: '处理完的数据'});
};
}
const testWorker = makeWorker (work);
testWorker ('传入要处理的数据').then (message => {
console.log ('接收处理完的数据:-----' + message);
});