【发布时间】:2020-11-09 16:12:37
【问题描述】:
我正在使用函数replaceStr() 来替换body 标签中的一些字符串。如果 html 页面很小,则替换不明显。但是如果 html 页面更大更复杂,你会注意到它。替换是阻塞浏览器。我的问题是,如何使替换非阻塞?替换对页面并不重要,因此它可以在浏览器不忙时在后台发生。我尝试使用 async 和 await,但我认为 replaceWith() 函数无法处理 Promises,这就是为什么它不能使用 async/await时间>。但那你怎么能做到呢?
function replaceStr(myStrArr) {
const container = $('body :not(script)');
myStrArr.map((mystr) => {
container
.contents()
.filter((_, i) => {
return i.nodeType === 3 && i.nodeValue.match(mystr.reg);
})
.replaceWith(function () {
return this.nodeValue.replace(mystr.reg, mystr.newStr);
});
});
}
感谢您的帮助。
【问题讨论】:
-
您是否尝试将
async添加到函数定义中,例如async function replaceStr(myStrArr)...??? -
@UmairKhan 这是我做的第一件事。仍然阻塞。
-
@UmairKhan 当所有方法都同步时,使用
async毫无意义 -
@charlietfl 不,因为它正在操纵 DOM?
标签: javascript jquery async-await asynchronous-javascript