如何让JavaScript按预期顺序渲染页面元素?
解决Loader无法及时显示的问题
问题现象
- 保留数据请求和图表处理代码时,Loader不会及时显示,需等所有处理完成后才短暂出现,随即被图表替换。
- 注释请求代码后,“Data is not awailable”会立即显示(不符合预期),之后Loader出现又瞬间消失,最终仅保留提示信息,且截图显示提示与Loader同时出现。
推测原因:JavaScript为单线程执行模型,会先同步完成所有操作,再一次性触发浏览器渲染,导致Loader的渲染被阻塞,无法按预期及时显示。
相关代码
HTML代码
<div class="main-container-right"> <!-- Графики --> <div class="graph-container" style="display: none;"> <div id="mass-time-graph-container" class="derivative-graph-container"> -</div> <div id="temperature-graph-container" class="temperature-graph-container">-</div> </div> <div class="no-data-message data-not-awailable" style="display: none;">Data is not awailable</div> <div class="no-data-message data-loading" style="display: none;"> <img class="waiting-animation" src="img/loading.gif" title="Данные подгружаются" style="margin-left: 5px; cursor: pointer;"> <div>Data is loading</div> </div> <!-- END Графиков --> </div>
JavaScript代码
// -- Выбор испытания $('body').on('click', '.tr-content', function(){ $('.data-not-awailable').fadeOut(1) // -- THE Message should be display none $('.graph-container').fadeOut(1) // -- THE Loader should display $('.data-loading').fadeIn() // -- SOME code that takes 2-5 second $('.graph-container').fadeOut(1) // -- THE Loader should display none $('.data-loading').fadeOut(1) // -- THE Message should be display $('.data-not-awailable').fadeIn(1) })
解决方案
将耗时的逻辑代码封装为独立函数,通过window.setTimeout将其放入浏览器事件队列,让浏览器先完成Loader的渲染操作,再执行后续耗时逻辑。注意需传入函数引用,而非直接执行函数。
修改后的示例代码:
// -- Выбор испытания $('body').on('click', '.tr-content', function(){ $('.data-not-awailable').fadeOut(1) $('.graph-container').fadeOut(1) $('.data-loading').fadeIn() // 封装耗时逻辑为独立函数 function processSelectedTest() { // -- 此处放入原有的耗时处理代码 $('.graph-container').fadeOut(1) $('.data-loading').fadeOut(1) $('.data-not-awailable').fadeIn(1) } // 延迟执行,给浏览器留足渲染Loader的时间 window.setTimeout(processSelectedTest, 100) })
内容的提问来源于stack exchange,提问作者Viktor Kuryshev
相关产品推荐
相关产品推荐

