javascripthtmlbrowserspinnerloading

How to manually show tab loading indicator via javascript?


I'm talking about an icon that is displayed on a tab during page loading.

Chrome:

enter image description here

Firefox (with TreeTab plugin):

enter image description here

You get the idea. I want to make it seem like the page is loading, when it's already loaded. Some event fires is javascript and then the tab looks like it's being loaded. Is there a way to do that?

One way I can think of is to replace a favicon with a spinner, but I'm not sure if it's possible to change on the fly and even if it is, it would be a hassle to make it cross-browser.


Solution

  • I don't think it is a good idea to do it, you'll make your users do a lot of useless requests, and this kills trees : /

    IMO, it's better to do all you have in the page itself, and let the browser's UI do his own stuff.

    But since I liked the challenge, here is one hacky way :

    Loading an iframe will trigger this icon in both chrome and Firefox[1], so you could ,

    [1] It seems that Firefox does trigger the icon only if it was triggered when the document was still loading.

    In code :

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