Search code examples
jquerycycle-plugin

Jquery img.load question


I am using the jQuery cycle plugin to cycle through some images. These images are all contained inside a DIV. I don't want the cycle plugin to run until after all of the images have loaded, or at least the first 4 or 5 so that an image doesn't appear that isn't loaded yet. Is there an easy way of doing this?

I tried adding a class 'lastImg' to the last img in the div and adding a 'load' event to that e.g.

Markup
<div id='cycle'>
  <img src=''/>
  <img src=''/>
  <img src='' class='lastImg'/>
</div>

JQuery
    $('lastImg').load(function(){
      $('#cycle').cycle({..});
    });

This seems okay in Chrome and FF, admittedly it's a little flakey (sometimes it doesn't work, maybe if the image is in the cache?) and not at all in IE (surprise, surprise...).

Any other suggestions on how I can do this?


Solution

  • Markup:

    <div id='cycle'>
      <img src='path1' class='preload' />
      <img src='path2' class='preload' />
      <img src='path3' class='preload'/>
    </div>
    

    Try this:

    var cyclerLoaded = false;
    var numberOfPreloaded = 0;
    
    function imageLoaded()
    {      
      numberOfPreloaded++;
    
      if (numberOfPreloaded >= 4 && !cyclerLoaded)
      {
        $('#cycle').cycle({..});
        cyclerLoaded = true;
      }
    }
    
    $(document).ready(function()
    {      
    
      $('img.preload').each(function()
      {
        // Get image instance.
        var image = new Image();
        image.src = $(this).attr('src');
    
        if (image.complete)        
          imageLoaded();        
        else        
          image.onload = imageLoaded;
    
      });
    
    });
    

    ...where the preload class is attached to all images you want to preload.