开发者

Check if image loaded before jquery plugin starts

For e.g I have a imageslider plugin.

<di开发者_C百科v class="images">
    <img src="1.jpg"/>
    <img src="2.jpg"/>
    .... 
</div>
$('.images').slider();

How can I specify in the plugin(any skeleton) that I want to start the plugin only when all images are loaded? Is it like e.g using a .load() method and adding to a variable everytime an image has loaded. Then once it reaches total number of images, call the plugin? But how can I 'pause' the plugin?

Thanks everyone, but I did mention IN a skeleton jquery plugin itself, how would i call the plugin after the images have loaded?


$(window).load(function() {
  $('.images').slider();
});

$(window).load will wait until all images are loaded on the page.

If you need to know when the images have finished loading in that particular div, please see the answers in this question: How to know when all images inside a specific "div" are loaded?


You can execute the plugin on the window.load event like so:

$(window).load(function () {
  $('.images').slider();
});

This is as opposed to the much more commonly used document.ready event:

$(document).ready(function () {
  $('.images').slider();
});

The key difference is that the latter will execute when the DOM is finished loading, while the former will wait until all resources referenced by the DOM are loaded. Note that if another resource is taking a long time to load even after the images are ready, then it will hold up the plugin until it loads or times out.


You can try this which will initialize the plugin after all the images are loaded.

$(function(){
   var imageCount = $(".images img").length;
   $(".images img").load(function(){
       imageCount--;
       if(imageCount == 0){
          $(this).parent().slider();
       }
   });
});


To check for all the images in just that element is a little tricky, but can be done.

//gather the total number of images
var imageNum = $('.images').find('img').length;
var imagesLoaded = 0;
//setup a load event for each img
$('.images img').each(function(){
    //load event will fire inconsistently in IE/FF so we create a new dom element but don't insert it
    $('<img>').load(function(){
        imagesLoaded++;
        //all images are loaded so fire the slider
        if(imagesLoaded == imageNum){
            $('.images').slider();
        }
    //we set the new img to have the src of the current image
    }).attr('src', $(this).attr('src'));
});

It's a little clunky, but should work.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜