Reputation: 79
I'm trying to build a preloader that actually represents a "percentage" of loaded content. Not necessarily by a number, but using an animated box (scaling from left to right of window). Currently, I'm using this code to determine how many images are on the page, and build a grid when all the images are loaded.
$(document).ready(function() {
num_images = $("img").length;
img_counter = 0;
$("img").css("display", "none");
$(".grid-item").each(function() {
$(window).load(function() {
img_counter++;
if (img_counter == num_images) {
console.log(num_images);
$("img").css("display", "block");
$('.grid').masonry({
itemSelector: '.grid-item',
isAnimated: true
});
}
});
});
});
Then, on window.load I have a preloader that adds a class of "loaded".
$('.preloader').addClass('loaded');
setTimeout(function() {
$('.content').css('opacity', 1);
$('.preloader').css({'transform': 'translateY(-50px)'});
}, 500);
This all gives the illusion that there is a loading feature, but it's not actually showing the "loading" process. How can I determine how much of the content is loaded and display that with the width of the preloader?
Here's a basic test page I'm working with. Thanks a ton in advance! I don't necessarily need answers, but guidance or direction.
http://andyrichardson.design/masonry/
Upvotes: 1
Views: 65
Reputation: 34180
Add an onload function for the images and increase the counter when the pnload function trggers (which mean that the image is loaded)
$(document).ready(function() {
num_images = $("img").length;
img_counter = 0;
$('img').load(function(){
img_counter++;
// do your other stuff here
});
}
Upvotes: 1