Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Play Preloading Screen until specific things are loaded

a little background.
Currently, I have a preloading screen that shows before the page is loaded for a set time. What I want is to be able to detect whether several elements are loaded and then ending the preloading screen rather then having a set time for the preloading screen to end.

In my fiddle, I would like to detect if the images have been fully rendered and loaded and then ending the screen and I would also like to understand and know how to do this for any other element such as a random div or paragraph if possible.

fiddle: https://jsfiddle.net/jzhang172/Lyv17L0n/1/

$(document).ready(function() {
 
    setTimeout(function(){
        $('body').addClass('loaded');
        $('h1').css('color','#222222');
    }, 500);
 
});
.loaded{
transition:1s;
}


.content{
  background:gray;
  height:500px;
  width:100%;
  
}

#loader-wrapper{
  position:fixed;
  background:black;
  top:0;
  bottom:0;
  left:0;
  right:0;
  transition:1s;
  
}
.loaded #loader-wrapper{
  opacity:0;
}
.loader-section{
  position:fixed;
  top:0;
  bottom:0;
  background:red;
  z-index:5;
  width:51%;
  transition:1s;
    opacity:1;
  
}
.section-left{
  left:0;
}
.section-right{
  right:0;
}


.loaded .loader-section.section-left{
  opacity:0;
  transform:translateX(-100%);
  transition:1s;
}
.loaded .loader-section.section-right{
    opacity:0;
  transform:translateX(100%);
  transition:1s;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
      <div id="loader-wrapper">
<div id="loader"></div>
<div class="loader-section section-left"></div>
<div class="loader-section section-right"></div>
    </div>
  <div class="content">
    <img src="https://upload.wikimedia.org/wikipedia/en/2/22/Kirby_Wii.png">
     <img src="https://upload.wikimedia.org/wikipedia/en/2/22/Kirby_Wii.png">
      <img src="https://upload.wikimedia.org/wikipedia/en/2/22/Kirby_Wii.png">
       <img src="https://upload.wikimedia.org/wikipedia/en/2/22/Kirby_Wii.png">
       
  </div>
  
</body>
like image 387
Snorlax Avatar asked Feb 07 '26 18:02

Snorlax


1 Answers

You can use this plugin: https://rawgit.com/alexanderdickson/waitForImages/master/dist/jquery.waitforimages.js

$('body').waitForImages(

function() {
    ...CODE FOR EACH LOAD...
}, function(loaded, total) {
    if(loaded / total == 1){
       ...CODE FOR FULLY LOAD...
    }
});

You can modify that plugin to get divs and txt. But mostly images are the ones that takes time to load.

you can check this plugin working:

http://jsfiddle.net/2sc0rtzL/

like image 187
Aschab Avatar answered Feb 09 '26 10:02

Aschab



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!