Search code examples
javascripthtmlcsspreloaderimage-preloader

How to preload a webpage before showing it?


I have created a simple webpage with several images, but when a user visits it, the browser loads the images one at a time, instead of all at once.

I want instead to first show a "loading" gif in the center of the page and then, when all the images are downloaded, show the entire webpage to the user at once..

How can I do this?


Solution

  • You can show a loader image by putting it somewhere im <img> tag and use below js code to hide it later on when all images are shown:

    window.onload = function(){
      var el = document.getElementById('elementID');
      el.style.display = 'none';
    };
    

    Where elementID is supposed to be the id of loader element/tag.


    The load event fires when all images/frames/external resources are loaded, so by the time that event fires, all images are loaded and we therefore hide the loading message/image here.