JensB
JensB

Reputation: 6850

Load images in order, with delay, fallback for no script

I'm wondering if anyone has a nice clean solution to loading images from top to bottom of a page, waiting for the previous image to load before going to the next. And in case the user dosent have javascript fall back on a regular <img> tag.

There are quite a few lazy loading plugins, but I would like to load all images as fast as possible in the order they appear on the website.

The reason for this is that each image is rather large, and the user will look through them from top to bottom in a rather slow fashion.

Upvotes: 3

Views: 1405

Answers (3)

A.B
A.B

Reputation: 20445

try this, first add this css

   img{display:none;}

jquery

   $("img").each(function(index, value){
   $(this).delay(300*index).fadeIn();   


   });

for fallback you can do this , add this jquery first that will run only if js enabled

$(function(){$('body').addClass('jse');});

then this

  $("img").each(function(index, value){
   $(this).delay(300*index).fadeIn();   


   });

and in css, that will onle be applied if jquery worded and body has class .jse

 .jse img {display:none;}

Upvotes: 0

Johan Karlsson
Johan Karlsson

Reputation: 6476

Here's how you can do it:

$(document).ready(function () {
    var $images = $("img");
    //First hide all images
    $images.hide();

    function lazyLoad(num) {
        $images.eq(num).fadeIn(function () {
            if (num != $images.length) {
                lazyLoad(++num);
            }
        });
    }
    //When first has loaded start fading in
    $images.eq(0).load(function () {
        lazyLoad(0);
    });
});

Check it out here: JSFiddle

Upvotes: 0

code_monk
code_monk

Reputation: 10120

interesting question. my approach would be something like this

$(function(){

  var loadNext = function(){
    var next_guy = $('#imgz img[x-src]').first();
    next_guy.prop('src', next_guy.attr('x-src'));
    next_guy.removeAttr('x-src');
    
  };
  
  $('#imgz img').on('load',loadNext);
  
});
#imgz img {
  width: 250px;
  border: 1px dotted gray;
  clear: both;
  display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="imgz">
  <img src="http://i.imgur.com/mThaO.jpg" />
  <img x-src="http://i.imgur.com/DO1kZ.jpg" />
  <img x-src="http://i.imgur.com/lD2HS.jpg" />
  <img x-src="http://i.imgur.com/4vqE3.jpg" />
  <img x-src="http://i.imgur.com/TXXbx.jpg" />
  <img x-src="http://i.imgur.com/TF3z2.jpg" />
</div>

Upvotes: 2

Related Questions