javascript - Having multiple imageLoaded calls on 1 page and making sure each call is complete before progressing -


i have 3 sections on page contain lots of images of various sizes, need make sure each of these 3 sections images have loaded before continue applying transitions etc fading sections in etc.

i think know need i'm not sure execute it. need create deferred object monitors each of these calls when complete resolve deferred object , run deferred.when or deferred.done method, sound right? i'm not sure how this?

i'm using imagesloaded plugin , code looks this:

js

    $(function () {       var def1 = $.deferred();     var def2 = $.deferred();     var def3 = $.deferred();     var def = $.when(def1, def2, def3);       $('.set1').imagesloaded(function () {         console.log('set 1 ready');          def1.resolve();     });      $('.set2').imagesloaded(function () {         console.log('set 2 ready');          def2.resolve();     });      $('.set3').imagesloaded(function () {         console.log('set 3 ready');          def3.resolve();     });       def.done(function () {         console.log('ready');     });  }); 

js fiddle http://jsfiddle.net/dkzrv/1/

$(function () {  function loadimages(selector) {     var dfd = $.deferred();      /*     ...do work load images...     if success,  dfd.resolve()/dfd.resolvewith(...)     if failure,  dfd.reject()/dfd.rejectwith(...)     indicate progress, dfd.notify()/dfd.notifywith(...)     */      $(selector).imagesloaded(function () {         var setresult = "dummy data";         dfd.resolve(setresult);     });      /*     if return dfd directly,      can canceled via .reject() outside.     allow outside canceling return dfd.     */     return dfd.promise(); }  //run multiple deferreds in parallel , wait complete $.when $.when(loadimages('.set1'), loadimages('.set2'), loadimages('.set3'))     .done(function(set1result, set2result, set3result) {         //all resolved     })     .fail(function() {         //one or more failed          //if want know one,          //you have save reference each of          //the loadimages calls , determine through          //their individual .failure()'s                 });  }); 

http://jsfiddle.net/dkzrv/4/

the $.when() function utility wraps multiple deferreds one. because returns deferred of own, can call .done() , fail() , treat other deferred.

for future reference, .then() controlling serial tasks , $.when() parallel tasks.

the loadimages() function wrap loadimages plugin in deferred make more general.


Comments

Popular posts from this blog

Detect support for Shoutcast ICY MP3 without navigator.userAgent in Firefox? -

web - SVG not rendering properly in Firefox -

java - JavaFX 2 slider labelFormatter not being used -