强制浏览器立即重新绘制dom元素 [英] Force browser to immediately repaint a dom element

查看:171
本文介绍了强制浏览器立即重新绘制dom元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在一些dom元素中插入一个巨大的html标记,这将需要一段时间。这就是为什么我要显示一些预加载器指示器的原因。我有两个块:#preloader和#container。某些代码会先显示预加载器,然后再开始粘贴大的html标记。

I need to insert a huge html markup to some dom element which will take awhile. It is a reason why I want to display some preloader indicator. I have two blocks: #preloader and #container. Some code displays the preloader firstly and then starts to paste a big html markup.

问题-在浏览器无法完成渲染html标记之前,未真正显示预加载器。我已经尝试了许多解决方案(其中许多描述如下这里),但仍然没有成功。

The problem - preloader hasn't really displayed until browser will not finish render html markup. I've tried a lot of solutions (a lot of them are described here) but still haven't success.

下面是一个示例:
https://jsfiddle.net/f9f5atzu/

<div id='preloader'>Preloader...</div>
<div id='container'>Container...</div>

#preloader {
  display: none;
  background-color: #f00;
  color: #fff;
  hight: 100px;
  text-align: center;
  padding: 10px 20px;
}

#container {
  background-color: #ccc;
}


setTimeout(function() {
  // Define variables
  let domPreloader = document.getElementById('preloader');
  let domContainer = document.getElementById('container');
  const html = Array(100000).fill("<div>1</div>");

  // Display preloader
  domPreloader.style.display = 'hide';
  domPreloader.offsetHeight;
  domPreloader.style.webkitTransform = 'scale(1)';
  domPreloader.style.display = 'block';

  // Render a big html
  domContainer.innerHTML = html;
}, 1000);

该问题是否有解决方案?

Is there any solutions for the problem?

推荐答案

这样做的方式是,您没有在预加载器的显示和'big html'的显示之间释放对浏览器的控制。

The way you did it, you're not releasing control to the browser between the display of the preloader and the display of the 'big html'.

而不是将整个块封装在 setTimeout()中,您应该仅更改呈现部分。

Rather than encapsulating this whole block inside a setTimeout(), you should just differ the rendering part.

请尝试以下方法:

// Define variables
let domPreloader = document.getElementById('preloader');
let domContainer = document.getElementById('container');

// Display preloader
domPreloader.style.webkitTransform = 'scale(1)';
domPreloader.style.display = 'block';

// Render a big html
setTimeout(render, 100);

function render() {
  const html = Array(100000).fill("<div>1</div>");
  domContainer.innerHTML = html;

  // Hide preloader
  domPreloader.style.display = 'none';
}

JSFiddle

这篇关于强制浏览器立即重新绘制dom元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆