1

I am currently using jQuery "addClass" and "removeClass" to remove the preloader. I want the preloader page to be removed when all web content is loaded. Setting a timeout function seems to work fine but I cannot seem to get to do the same when the entire site is finished loading, as in real time loading. Some help is highly appreciated.

//..HTML..//

<div class="loader-wrapper">
</div>

//..CSS..//

.loader-wrapper {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
}

.loaded .loader-wrapper {
-webkit-transform: translateY(120%);
-ms-transform: translateY(120%);
transform: translateY(120%);
-webkit-transition: all 1s 0.5s ease-out;
transition: all 1s 0.5s ease-out;
}

//..jQuery..//

<script>
  $("body").removeClass('loaded');
</script>

<script>
$( window ).load(function() {
 $("body").addClass('loaded');
});
</script>


//..For reference this works perfectly..//

<script>
$(document).ready(function() {

setTimeout(function() {
$("body").addClass('loaded');
}, 1800)

});
</script>
Lord Eww Lel
  • 143
  • 1
  • 2
  • 11
  • 2
    Any specific reason for having the JS code in two separate script tags? – George Nov 25 '16 at 10:20
  • It looks a bit cleaner to me. – Lord Eww Lel Nov 25 '16 at 10:22
  • Fair enough, personally I wouldn't recommend it [as there are reasons against it](http://stackoverflow.com/questions/6451156/multiple-versus-single-script-tags) but whatever. What does your html look like and are you doing any ajax calls? – George Nov 25 '16 at 10:27
  • I have included my html which is very simple and yes, I already have the jQuery Ajax. And I'll keep the script tags in mind for more complex sites. – Lord Eww Lel Nov 25 '16 at 10:32

2 Answers2

2

You can use a library, that validates when all images are loaded. For example imagesLoaded.

So your code may look something like that:

// DOM is ready
$(function() {
    // We have to make sure that all of the images are loaded in the container
    $('body').imagesLoaded( function() {
        // Images are loaded
        $('.loader').hide();
        $('img').show();
    });
});
img {
    display: none
}
<script src="https://code.jquery.com/jquery-3.1.1.js"></script>
<script src="https://npmcdn.com/imagesloaded@4.1/imagesloaded.pkgd.js"></script>

<span class='loader'>Loading ...</span>
<img width="200" src="https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-logo.png?v=9c558ec15d8a" />
Jordan Enev
  • 16,904
  • 3
  • 42
  • 67
-1
You can use the $(document).ready(function(){ // code  }); 

, if you are waiting the web page to load completely.

Lego
  • 15
  • 2
  • Please read [this](http://stackoverflow.com/questions/5182016/what-is-the-difference-between-window-load-and-document-ready) – George Nov 25 '16 at 10:42