I am trying to reduce my website's loading time by placing a loading effect in the place of all img tags, and once the image loads the loading effect should disappear and actual image should fade in in the container.
My current try looks like the following:
Images are placed in markup as follows:
foreach ( $results['gallery'] as $gallery ) {
$imgName = $gallery->photo;
array_push($pictures, $gallery->photo);
echo '<img class="photo" src="'.$path.$imgName. '" alt="">';
}
js:
$(document).ready(function() {
$(".photo").hide().each(function() {
var loader = new Image();
$(loader).hide();
$(loader).on('load', function() {
console.log($(this).attr('src') + " loaded");
$(this).fadeIn(700);
})
loader.src = $(this).attr('src');
});
});
The desired outcome is to place each src into an Image() object and once that manages to load the picture in the background, the current .photo should fade in.
However, what actually happens is that even though the console.log statement has not yet appeared in the console, the image is already shown and the user can see that the browser is slowly loading the image (we are talking lots of 10+ MB pictures, so on a throttled connection its as if this piece of code wasnt even in the .js).
Another issue with this current approach is that images seem to start loading bottom to top of the markup (e.g. the very last picture in the markup is the first one to load), which I also havent managed to solve.
I have also tried initially putting the source in to data-src tag, iterating through them and loading them one by one in a similar fashion (utilising Image object), and on load the img tag would have their src set, however this has not worked at all. How could I modify my current approach so that the onload actually behaves?