简体   繁体   中英

Load overlay till page is rendered

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

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

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

This happens eg 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM