【问题标题】:change DOM while heavy function is running在繁重的功能运行时更改 DOM
【发布时间】:2020-09-01 08:16:37
【问题描述】:

我想在一个繁重的函数阻塞主线程时显示一个加载微调器like this

我的代码基本上是这样的:

image.onload = function onLoad() {
  document.getElementById("loading-spinner").style.display = "block";
  run_heavy_function(this);
};

加载微调器仅在功能完成后显示。这不是我想要的。

我遇到了一些使用 setTimeout 之类的解决方案。但这对我来说似乎不是一个好主意。使用纯 JavaScript 在 ES6 的后台进程中更改 DOM 的正确方法是什么?

【问题讨论】:

标签: javascript asynchronous dom ecmascript-6


【解决方案1】:

解决这个问题的一个简单模式是事件通信:

const loaderStart = new Event('loaderStart');
const loaderEnd = new Event('loaderEnd');
const spinner = document.getElementById("loading-spinner");

image.onload = function onLoad() {
  spinner.dispatchEvent(loaderStart);
  run_heavy_function(this);
  spinner.dispatchEvent(loaderEnd);
};

spinner.addEventListener('loaderStart', function(){
   this.style.display = "block";
});

spinner.addEventListener('loaderEnd', function(){
   this.style.display = "none";
});

【讨论】:

    猜你喜欢
    • 2022-11-11
    • 2018-06-22
    • 2013-05-28
    • 1970-01-01
    • 2011-08-10
    • 2011-01-25
    • 1970-01-01
    • 1970-01-01
    • 2011-08-05
    相关资源
    最近更新 更多