0

I am trying to make it so that there is an overlay on the page till the page is fully rendered. I can do this by using timeouts but that is probably not the right way to do this. Is there a better way to achieve this?

Issue I am having is that $(window).load doesn't trigger.

JS:

$(document).ready(function() {
  $(".overlay").fadeIn();
  $(window).on('load', function() {
    $(".overlay").fadeOut();
  });

});

CSS:

.overlay{
    display: none;
    position: fixed;
    padding: 0;
    margin: 0;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, .3);
    opacity: .8;
    pointer-events: none;
}

JSFiddle Demo

TrickMonkey
  • 155
  • 1
  • 8
  • https://codepen.io/bartwal/pen/OXOoWN – Gurmeet Singh Jan 21 '18 at 07:32
  • You must set overlay to display: block; and change it to display:none when the window is loaded or the document is rendered. You can read the difference between them here https://stackoverflow.com/a/40936951/4700464 – Gurmeet Singh Jan 21 '18 at 07:35

2 Answers2

2

This will help you. First document is loaded then window is loaded.

$(document).ready(function() {
  $(".overlay").fadeIn();
 });
  $(window).on('load', function() {
     $(".overlay").fadeOut();
   });

For more ref - http://javarevisited.blogspot.in/2014/11/difference-between-jquery-document-ready-vs-Javascript-window-onload-event.html?m=1

Negi Rox
  • 3,828
  • 1
  • 11
  • 18
2

jQuery's document.ready event is fired asynchronously and hence may fire after the window.load event in some cases.

This happens e.g. in your fiddle, because there is almost nothing on the page to load.

Your fiddle can be fixed using this js and setting the Load Type of the js to "No wrap - in < body >":

$(".overlay").fadeIn(function(){
  console.log('fadedin');
});

$(window).on('load', function(){
    $(".overlay").fadeOut(function(){
    console.log('fadedout');
  }); 
});

Try also:

$(document).ready(function(){
    $(".overlay").fadeIn(function(){
    console.log('fadein');
  });
});

$(window).on('load', function(){
    $(".overlay").fadeOut(function(){
    console.log('fadedout');
  }); 
});

to see that the document.ready event is fired after the window.load event.