开发者

$.get to load and show content in div only once content, including images, are ready

I am using a get to load content to a div and 开发者_运维技巧then show it. Works great, very easy.

$.get($(this).attr("href"), function (data) {
  $('#boardData').html(data);
  $('#boardContent').show();
  $('#BoardImages a').lightBox();
});

I would like to only show the div, my $('#boardContent').show();, once all of the images have loaded from my data that I got via my get.


The way that I've done this -- you really probably only need to worry about elements that get their content from elsewhere, like images -- is to keep a count of the elements that need to load and use load event handlers on all those elements. When all of the elements are loaded, have your handler trigger the show. As a backstop you'll want to set a timer that will trigger the show in case some of the elements get loaded before your handler is applied.

$.get($(this).attr("href"), function (data) {
      var images = $(data).find('img');
      var imageCount = images.length;
      var loaded = 0;
      var timer = setTimeout( function() {
               timer = null;
               $('#boardContent:hidden').show();
      }, 10000 );
      images.load( function() {
          ++loaded;
          if (loaded >= imageCount) {
             if (timer) clearTimeout(timer);
             timer = null;
             $('#boardContent:hidden').show();
          }
      });

      $('#boardData').html(data);
      $('#BoardImages a').lightBox();
});


You could scan the HTML data for <img> elements, then run them through a preloader whose "oncomplete" callback you specify to contain $('#boardContent').show();

Edit:

Here's a plugin I've written for myself on another project...

        jQuery.extend(jQuery, {
            imagesToLoad: 0,
            loadedImages: [],
            preloadImages: function(){
                var settings = {
                    urls : [],
                    begin : function(){},
                    each : function(){},
                    complete : function(){},
                    scope: window
                };
                jQuery.extend(settings, arguments[0]);
                var images = [];

                jQuery.imagesToLoad = settings.urls.length;

                settings.begin.call(settings.scope, settings.urls);
                for(var i = 0; i = jQuery.imagesToLoad){
                            settings.complete.call(settings.scope,jQuery.loadedImages);
                        }
                    }
                    images[i].src= settings.urls[i];
                }
            }
        });
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜