如何通过javascript手动显示标签加载指标?

时间:2016-09-01 10:43:10

标签: javascript html browser spinner loading

我说的是在页面加载过程中显示在选项卡上的图标。

Chrome:

documentation

Firefox(使用TreeTab插件):

enter image description here

你明白了。我想让它看起来像页面正在加载,当它已经加载。一些事件触发器是javascript,然后选项卡看起来像是正在加载。有没有办法做到这一点?

我能想到的一种方法是用旋转器替换一个图标,但我不确定它是否可以即时更改,即使它是,它也会让它成为跨浏览器的麻烦。

2 个答案:

答案 0 :(得分:5)

  

我不认为这样做是个好主意,你会让你的用户做很多无用的请求,这会杀死树:/

IMO,最好在页面中完成所有工作,并让浏览器的用户界面自行完成。

但是因为我喜欢挑战,所以这是一种愚蠢的方式:

加载iframe会在chrome和Firefox [1] 中触发此图标,所以你可以,

  • 在文档中追加iframe,
  • 将其src设置为一些巨大的文档,
  • 加载iframe,使用?缓存黑客再次设置
  • 定期检查持续时间是否已过,这样您就可以删除iframe的src。

[1]似乎Firefox只在文档仍在加载时触发了图标才会触发。

在代码中:



// how to use : 
showTabLoader(25000);

// takes duration in ms as only parameter
function showTabLoader(duration) {

  if (!duration) return;

  var now = performance.now();
  // To avoid flickering, you need some big document
  // Please change this url in your script, wikimedia may not be happy with us.
  var url = 'https://upload.wikimedia.org/wikipedia/commons/3/35/Viborg_Katedralskole_Symmetrical.jpg';

  var iframe = document.createElement('iframe');
  iframe.style.display = 'none';
  document.body.appendChild(iframe);
  iframe.onload = function() {
    if (performance.now() - now < +duration) {
      this.src = url + '?' + Math.random();
    }
  };
  var check = function(time) {
    if (time - now > +duration) {
      iframe.src = '';
      iframe.parentNode.removeChild(iframe);
      return;
    }
    requestAnimationFrame(check);
  }
  requestAnimationFrame(check);
  iframe.src = url;

}
&#13;
&#13;
&#13;

答案 1 :(得分:0)

Alternitive:

没有显示网页实际加载过程的功能。但你可以手动完成,就像你说的那样!

即使在加载了所有图像之后,当页面完全加载时,下面的事件也会开始运行:

$(window).on('load', function() {
  // do stuff
});

所以你可以做的是设置你的 html

<div class="preloader">
  // your loader here, animations, video, gif, anything you want
</div>
<div class="main" style="display: none;">
  // the page
</div>

和你的 jquery 是这样的:

$(window).on('load', function() {
  setTimeout(function() {
    $('.preloader').css('display', 'none');
    $('.main').css('opacity', '1');
  }, 5000); // <-- 5seconds
});

你有手动加载功能!效果很好。

示例网站:ifly50

编辑:

添加了代码段

代码段:

$(window).on('load', function() {
  setTimeout(function() {
    $('.preloader').css('display', 'none');
    $('.main').css('display', 'block');
  }, 3000); // <-- 3 seconds
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="preloader">loading</div>
<div class="main" style="display: none;">main</div>