微任务创建方式:
- Promise.then(()=>{})
- Mutation Observer()
- queueMicrotask()
本文主要介绍queueMicrotask()的使用。
queueMicrotask的使用
- Window 或 Worker 接口的 queueMicrotask() 方法,将微任务加入队列以在控制返回浏览器的事件循环之前的安全时间执行。
- 语法:queueMicrotask(() => {/* … */});
- 参数:function
- 返回值:无
- 代码示例:
MyElement.prototype.loadData = function (url) {
if (this._cache[url]) {
queueMicrotask(() => {
this._setData(this._cache[url]);
this.dispatchEvent(new Event("load"));
});
} else {
fetch(url)
.then((res) => res.arrayBuffer())
.then((data) => {
this._cache[url] = data;
this._setData(data);
this.dispatchEvent(new Event("load"));
});
}
};
queueMicrotask的使用浏览器支持情况
![请添加图片描述](https://img-blog.csdnimg.cn/f5a032e3e04d44ee89543c85a61e67be.png)