html - Hide subset of background-images until children() are fully loaded with Jquery -


i have articles, each of them containig list multiple list items. every list item has background-image defined. html looks this:

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

i hide list items until every image loaded , im trying each article.

my first attempt use 2 nested loops feels bit akward , 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 current article                 }              });                                          n++;         });     }); } 

is there more elegant way of doing ?

just start them visibility:hidden , show them when window.load event fires.

css

.loading li{     visibility:hidden; } 

html

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

and jquery

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

if want show images in each article own images have loaded code pretty close, can improve following

  • handle error event well
  • cache selections
  • bind load , error events before setting src correctly handle cached images

here implementation

$(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;         });      }); }); 

demo at http://jsfiddle.net/gaby/2athq/


Popular posts from this blog

How to calculate SNR of signals in MATLAB? -

c# - Attempting to upload to FTP: System.Net.WebException: System error -

ios - UISlider customization: how to properly add shadow to custom knob image -