Jquery img.load question

感情迁移 提交于 2019-11-30 05:32:08

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.

Why not hookup the cycle plugin in document's load event? Document's load event fires when all the artificats have been downloaded. [ready event fires when DOM is available.]

Try

$(document).load(function() { //your cycle plugin hookup } );

A better way will be to write a function to preload sufficient number of images and then call cycle function. Because how, when and in what order the images in page are loaded may vary by browser or other circumstances.

Here is a great little function at ajaxian that preload all images available in even the stylesheets referenced in page.

One thing that's wrong in your code is you are using $('lastImg'), but it should be $('.lastImg').

Thus, your code will never run at all.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!