Force browser to immediately repaint a dom element

耗尽温柔 提交于 2019-12-02 16:56:56

问题


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.

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.

An example is avalable below: 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?


回答1:


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'.

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

Please try something along those lines:

// 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



来源:https://stackoverflow.com/questions/38724180/force-browser-to-immediately-repaint-a-dom-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!