1

I have some articles, each of them containig a list with multiple list items. Every list item has a background-image defined. The HTML looks something like this:

<article>
  <ul>
    <li><!-- background-image--></li>
    <li><!-- background-image--></li>
  </ul>
</article>

I would like to hide those list items until every image is loaded and im trying to do so for each article.

My first attempt was to use two nested loops but it feels a bit akward and complicated.

function preloader() {

    $('article').each( function(i) {        

        $(this).addClass('loading');

        var childNum = $(this).find('ul li').size();

        $(this).find('ul li').each( function(n) {

            var bgurl = $(this).css('background-image').replace(/url\(|\)|"|'/g,'');

            $('<img/>').attr('src', bgurl).load(function() {

                if (n == childNum) {

                    // remove class .loading from current article
                }

            });                             
            n++;
        });
    });
}

Is there a more elegant way of doing this ?

4

1 回答 1

0

只需启动它们并在事件触发visibility:hidden时显示它们。window.load

CSS

.loading li{
    visibility:hidden;
}

HTML

<article class="loading">
  <ul>
    <li><!-- background-image--></li>
    <li><!-- background-image--></li>
  </ul>
</article>

jQuery

$(window).load(function(){
   $('article.loading').removeClass('loading');
});

如果您想将每篇文章中的图像显示为已加载其自己的图像,那么您的代码非常接近,但您可以通过以下方式进行改进

  • 同时处理error事件
  • 缓存您的选择
  • 在设置正确处理缓存图像之前绑定loaderror事件src

这是一个实现

$(function () {
    var articles = $('article').addClass('loading');
    var urlRegExp = /(url\([\'\"]?)([^\'\"]+)/gi;

    articles.each(function(){
        var article = $(this),
            images = $('li', article).map(function(){
                return $(this).css('background-image').split(urlRegExp)[2];
            }).get(),
            imageCount = images.length;

        $.each(images, function(index, url){
           var img = new Image();
            $(img).on('load error', function(){
                imageCount--;
                if (imageCount === 0){
                    article.removeClass('loading');
                }
            })[0].src = url;
        });

    });
});

演示在 http://jsfiddle.net/gaby/2ATHQ/

于 2013-04-25T11:30:15.867 回答