【问题标题】:Show loader while document body is not loaded yet在文档正文尚未加载时显示加载器
【发布时间】:2019-11-09 20:41:36
【问题描述】:

有一些答案如何在加载元素时显示加载器。我的问题不一样。我想在加载文档正文之前显示加载器。

我有 ajax 调用

var url = window.location.origin+"/test.html";
showLoader();
$$.ajax({                                   
   type: "GET",                           
   url: url,                               
   success: function(data)                 
   {                                   
      document.open();                               
      document.write(data);                           
      document.close(); 
      hideLoader();                                                                                        
   }                                       
 }); 

问题是因为 test.html 有一些脚本会延迟文档正文的加载。它显示空白屏幕,直到未加载脚本并因此呈现文档正文。

知道如何在加载文档正文时显示加载器吗?

【问题讨论】:

  • 您正在使用 document.write(data); 和 test.html 覆盖 DOM 内容。因此,如果有进度条或类似的东西,它无论如何都会消失。您需要在 test.html 中包含一个加载器
  • 是的,但它仍然会在没有加载器的情况下显示空白页一两秒钟,直到由于我没有影响的头脚本延迟而没有呈现来自 test.html 的文档正文。
  • 在加载文档之前不能显示加载器,因为显示加载器的是文档。
  • 文档已加载,但文档正文尚未加载,因为脚本加载延迟渲染正文。
  • 使用 beforesend 启动加载器,在你完成所有逻辑后使用 always 来停止加载器,这是一个示例jsfiddle.net/4xhke5pt/1希望它有所帮助

标签: javascript html ajax dom


【解决方案1】:

您可以将静态页面加载器(使用 css 或图像)设置为页面的初始状态,然后在通过 AJAX 加载后立即用内容覆盖它。希望下面的例子能说明这个想法:

// imitating AJAX call for the content
setTimeout(() => {
  document.write('Content loaded')
}, 3000)
.loading {
  position: fixed;
  height: 1em;
  width: 1em;
  margin: auto;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
}
<div class="loading">Loading...</div>

【讨论】:

  • 这不能解决我的问题。我知道如何在加载 ajax 调用之前显示加载器,问题是关于成功加载 ajax 调用之间的时间和渲染文档正文之间的时间,因为头部中的一些脚本延迟渲染正文。
猜你喜欢
  • 2017-03-08
  • 2019-01-08
  • 1970-01-01
  • 2014-03-01
  • 2015-01-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-17
相关资源
最近更新 更多