Image preloader javascript that supports events












7















I am trying to find an image preloader script.



While i found a few, none of them supports an event that is triggered when preloading is finished.



Does anyone know of any script or jQuery plugin that will do this?



Hope this question is appropriate for stackoverflow - if not, feel free to remove it in an instant.










share|improve this question



























    7















    I am trying to find an image preloader script.



    While i found a few, none of them supports an event that is triggered when preloading is finished.



    Does anyone know of any script or jQuery plugin that will do this?



    Hope this question is appropriate for stackoverflow - if not, feel free to remove it in an instant.










    share|improve this question

























      7












      7








      7


      4






      I am trying to find an image preloader script.



      While i found a few, none of them supports an event that is triggered when preloading is finished.



      Does anyone know of any script or jQuery plugin that will do this?



      Hope this question is appropriate for stackoverflow - if not, feel free to remove it in an instant.










      share|improve this question














      I am trying to find an image preloader script.



      While i found a few, none of them supports an event that is triggered when preloading is finished.



      Does anyone know of any script or jQuery plugin that will do this?



      Hope this question is appropriate for stackoverflow - if not, feel free to remove it in an instant.







      javascript jquery image preloader preloading






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 25 '11 at 3:19









      SquareCatSquareCat

      3,54652668




      3,54652668
























          4 Answers
          4






          active

          oldest

          votes


















          28














          Here's a function that will preload images from an array and call your callback when the last one has finished:



          function preloadImages(srcs, imgs, callback) {
          var img;
          var remaining = srcs.length;
          for (var i = 0; i < srcs.length; i++) {
          img = new Image();
          img.onload = function() {
          --remaining;
          if (remaining <= 0) {
          callback();
          }
          };
          img.src = srcs[i];
          imgs.push(img);
          }
          }

          // then to call it, you would use this
          var imageSrcs = ["src1", "src2", "src3", "src4"];
          var images = ;

          preloadImages(imageSrcs, images, myFunction);




          And since we're now in the age of using promises for asynchronous operations, here's a version of the above that uses promises and notifies the caller via an ES6 standard promise:



          function preloadImages(srcs) {
          function loadImage(src) {
          return new Promise(function(resolve, reject) {
          var img = new Image();
          img.onload = function() {
          resolve(img);
          };
          img.onerror = img.onabort = function() {
          reject(src);
          };
          img.src = src;
          });
          }
          var promises = ;
          for (var i = 0; i < srcs.length; i++) {
          promises.push(loadImage(srcs[i]));
          }
          return Promise.all(promises);
          }

          preloadImages(["src1", "src2", "src3", "src4"]).then(function(imgs) {
          // all images are loaded now and in the array imgs
          }, function(errImg) {
          // at least one image failed to load
          });




          And, here's a version using 2015 jQuery promises:



          function preloadImages(srcs) {
          function loadImage(src) {
          return new $.Deferred(function(def) {
          var img = new Image();
          img.onload = function() {
          def.resolve(img);
          };
          img.onerror = img.onabort = function() {
          def.reject(src);
          };
          img.src = src;
          }).promise();
          }
          var promises = ;
          for (var i = 0; i < srcs.length; i++) {
          promises.push(loadImage(srcs[i]));
          }
          return $.when.apply($, promises).then(function() {
          // return results as a simple array rather than as separate arguments
          return Array.prototype.slice.call(arguments);
          });
          }

          preloadImages(["src1", "src2", "src3", "src4"]).then(function(imgs) {
          // all images are loaded now and in the array imgs
          }, function(errImg) {
          // at least one image failed to load
          });





          share|improve this answer


























          • Wow, thanks mate. This is great stuff! 100% !!

            – SquareCat
            Nov 25 '11 at 15:36






          • 2





            For completeness on this function, you could add onerror handlers, onabort handlers and a timeout such that you could still call your callback if one or more of the images had a problem loading and would never complete successfully. It will work fine as is if the images don't have errors loading.

            – jfriend00
            Nov 25 '11 at 15:46













          • Yes, that is quite nice. I was trying to show that, but I fell short.

            – Simon
            Nov 26 '11 at 14:17













          • Added versions of the preloadImages() function that use promises, both standard ES6 promises and jQuery promises.

            – jfriend00
            Nov 9 '15 at 17:43











          • It seems to me that new additions are missing img.src = src; after var img = new Image();

            – Andris Zalitis
            Dec 16 '15 at 7:42



















          2















          For a more robust solution, consider this PRELOADER function with a couple of callbacks (jsFiddle).



          Keeping it simple:



          In this example, I'm passing callbacks and an image hash inside an Object literal PRELOADER_OBJECT, then overriding the callbacks inside PRELOADER:



          // preloder object stores image hash
          // and event handler callbacks
          var PRELOADER_OBJECT = {

          imgArray:"http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg".split(" "),

          progressCallback : function( percent )
          {
          $( '#preloader_progress' ).html( 'preload progress complete : ' + percent + '%' );
          console.log( 'preload progress complete : ', percent );
          },

          completeCallback : function( scope )
          {
          // hide preload indicator, do something when finished
          console.log( 'preload complete!' );
          $( '#preloader_modal' ).delay( 1000 ).animate( { opacity : 0 }, function( )
          {
          $( '.preload_class' ).each( function( index )
          {
          $( this ).delay( index * 100 ).animate( { opacity : 0 } );
          } );
          } );
          }

          /*Localize params and create PRELOADER object.
          Needs to loadImages( ); iterate through hash and
          call onPreloadProgress( ) and onPreloadComplete( )
          each time until finished. If you're still within
          bounds of the image hash, call progressCallback( )
          recursively. When finished, fire onCompleteCallback( )*/

          var PRELOADER = function( object )
          {
          // preloader modal overlay
          this.modal = undefined;

          // progress indicator container
          this.progressIndicator = undefined;

          // image preload progress
          this.progress = undefined;

          // progress callback
          this.progressCallback = undefined;

          // complete callback
          this.completeCallback = undefined;

          // hash to store key : value pairs for image paths
          this.imgArray = undefined;

          // store images in preloadArray
          this.preloadArray = ;

          // initialize and localize our data
          this.initialize = function( )
          {
          // create preload indicator and overlay modal
          this.createPreloaderModal( );

          // image hash
          this.imgArray = object.imgArray;

          // progress callback event handler
          this.progressCallback = object.progressCallback;

          // complete callback event
          this.completeCallback = object.completeCallback;

          // load images
          this.loadImages( );
          };

          this.progressCallback = function( ) {}; // function to override

          this.completeCallback = function( ) {}; // function to override

          // load images into DOM and fire callbacks
          this.loadImages = function( )
          {
          var that = this;

          // iterate through hash and place images into DOM
          $.each( PRELOADER_OBJECT.imgArray, function( index, object )
          {
          this.image = $( "<img/>", { "src" : object, "class": "preload_class" } ).appendTo( 'body' );

          // mark progress and call progressCallback( ) event handler
          that.progress = Math.ceil( ( index / PRELOADER_OBJECT.imgArray.length ) * 100 );
          that.progressCallback( this.progress );

          that.preloadArray.push( this.image );
          } );

          // check for array bounds and call completeCallback( )
          if ( PRELOADER_OBJECT.imgArray.length )
          {
          this.progressCallback( 100 );
          this.completeCallback( this );
          }
          };

          // create modal to display preload data
          this.createPreloaderModal = function( )
          {
          this.modal = $( '<div/>', { 'id' : 'preloader_modal' } ).appendTo( 'body' );
          this.progressIndicator = $( '<h1/>', { 'id' : 'preloader_progress' } ).appendTo( this.modal );
          };
          };

          // trigger event chain when DOM loads
          $( document ).ready( function( )
          {
          // instantiate PRELOADER instance and pass
          // our JSON data model as a parameter
          var preloader = new PRELOADER( PRELOADER_OBJECT );

          // initialize preloader
          preloader.initialize( );
          } );


          };​



          With a site load large enough to require an image preloader, the modal text display could be easily modified to support a data-driven jQuery animation.






          share|improve this answer

































            0














            Preloading and loading are the same thing. You can insert the image (either create a new one or change the "src" attribute of an existing one) but hide the element using $("element").hide() or something similar. Before you do this, attach a load event handler like so:



            var images = ["src1", "src2", "src3", "src4"];
            var len = images.length;

            for(i=0; i<len; i++){
            $("parent element").html('<img id="new-img" style="display:none;" src="'+images[i]+'"/>');
            $("new-img").load(function(){
            //Your image is now "preloaded"

            //Now you can show the image, or do other stuff
            $(this).show();
            });
            }





            share|improve this answer


























            • Thank You, simon. I am trying to set this up for a contact map where there are parts of a country that are to be displayed, which are each PNGs, pretty huge. I want to preload the whole thing, then add a class name to its container to make it visible. That's pretty much all. But attaching a callback for triggering on load of a single image is not what i am looking for.

              – SquareCat
              Nov 25 '11 at 3:32











            • What do you mean by "pre-loading"? I assume you want to load it before the user needs it so that when he/she wants to see it, it doesn't take a millenium to show up. Use the above code to load the image, once it is loaded, you can store a reference to it so you can refer to it when the user needs to see it. This effectively pre-loads the image.

              – Simon
              Nov 25 '11 at 3:37











            • Thank you, i understand, but it is just not what i am looking for. I am trying to find a script that i can feed with an array of image sources, which loads them in the background and then triggers an event.

              – SquareCat
              Nov 25 '11 at 3:41











            • Perhaps my update will help. Otherwise, good luck.

              – Simon
              Nov 25 '11 at 3:53











            • Every time an image is done loading, do a var++, and if the var == the number of images to preload, run your "everything loaded" routine

              – Thilo Savage
              Nov 25 '11 at 4:23





















            0














            Preloading takes some extra work like creating new image elements, monitoring if they are all loaded and then replacing them with the existing ones in the DOM. However you may do this directly on the DOM <img> elements indefinitely many times without replacing them.



            We may use the Fetch API to access the images, wait until they are all downloaded within a promise.all() and then in one go just replace the src attributes of the img elements at the most suitable time by using window.requestAnimationFrame().



            In the following example I refresh the src attributes of the img elements 10 times. As per the delay, i am using the the time it takes up to load 4 images from an API. So once we have all images loaded i am immediately placing a new request by calling the same refreshImagesNTimes function recursively.



            You may of course chose to load as many image blobs as you like all at once and display them in groups in precise time intervals by using a simple setTimeout mechanism.






            function refreshImagesNTimes(nodeList,count = -1){
            var imgPromises = Array.from({length: nodeList.length})
            .map(_ => fetch("https://unsplash.it/480/640/?random").then(res => res.blob()));
            Promise.all(imgPromises)
            .then(function(blobs){
            window.requestAnimationFrame(_ => nodeList.forEach((img, i) => img.src = (window.URL || window.webkitURL).createObjectURL(blobs[i])));
            --count && refreshImagesNTimes(nodeList, count);
            });
            }

            var images = document.querySelectorAll("#container img");
            refreshImagesNTimes(images,10);

            #container {
            display: flex;
            flex-wrap: wrap;
            justify-content: space-evenly;
            align-items: center;
            margin: auto;
            width: 75vw;
            height: 56.25vw;
            background-color: #000;
            box-sizing: border-box;
            }

            img {
            width: 45%;
            height: 45%;
            background-color: thistle;
            }

            <div id="container">
            <img>
            <img>
            <img>
            <img>
            </div>








            share|improve this answer

























              Your Answer






              StackExchange.ifUsing("editor", function () {
              StackExchange.using("externalEditor", function () {
              StackExchange.using("snippets", function () {
              StackExchange.snippets.init();
              });
              });
              }, "code-snippets");

              StackExchange.ready(function() {
              var channelOptions = {
              tags: "".split(" "),
              id: "1"
              };
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function() {
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled) {
              StackExchange.using("snippets", function() {
              createEditor();
              });
              }
              else {
              createEditor();
              }
              });

              function createEditor() {
              StackExchange.prepareEditor({
              heartbeatType: 'answer',
              autoActivateHeartbeat: false,
              convertImagesToLinks: true,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: 10,
              bindNavPrevention: true,
              postfix: "",
              imageUploader: {
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              },
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              });


              }
              });














              draft saved

              draft discarded


















              StackExchange.ready(
              function () {
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f8264528%2fimage-preloader-javascript-that-supports-events%23new-answer', 'question_page');
              }
              );

              Post as a guest















              Required, but never shown

























              4 Answers
              4






              active

              oldest

              votes








              4 Answers
              4






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              28














              Here's a function that will preload images from an array and call your callback when the last one has finished:



              function preloadImages(srcs, imgs, callback) {
              var img;
              var remaining = srcs.length;
              for (var i = 0; i < srcs.length; i++) {
              img = new Image();
              img.onload = function() {
              --remaining;
              if (remaining <= 0) {
              callback();
              }
              };
              img.src = srcs[i];
              imgs.push(img);
              }
              }

              // then to call it, you would use this
              var imageSrcs = ["src1", "src2", "src3", "src4"];
              var images = ;

              preloadImages(imageSrcs, images, myFunction);




              And since we're now in the age of using promises for asynchronous operations, here's a version of the above that uses promises and notifies the caller via an ES6 standard promise:



              function preloadImages(srcs) {
              function loadImage(src) {
              return new Promise(function(resolve, reject) {
              var img = new Image();
              img.onload = function() {
              resolve(img);
              };
              img.onerror = img.onabort = function() {
              reject(src);
              };
              img.src = src;
              });
              }
              var promises = ;
              for (var i = 0; i < srcs.length; i++) {
              promises.push(loadImage(srcs[i]));
              }
              return Promise.all(promises);
              }

              preloadImages(["src1", "src2", "src3", "src4"]).then(function(imgs) {
              // all images are loaded now and in the array imgs
              }, function(errImg) {
              // at least one image failed to load
              });




              And, here's a version using 2015 jQuery promises:



              function preloadImages(srcs) {
              function loadImage(src) {
              return new $.Deferred(function(def) {
              var img = new Image();
              img.onload = function() {
              def.resolve(img);
              };
              img.onerror = img.onabort = function() {
              def.reject(src);
              };
              img.src = src;
              }).promise();
              }
              var promises = ;
              for (var i = 0; i < srcs.length; i++) {
              promises.push(loadImage(srcs[i]));
              }
              return $.when.apply($, promises).then(function() {
              // return results as a simple array rather than as separate arguments
              return Array.prototype.slice.call(arguments);
              });
              }

              preloadImages(["src1", "src2", "src3", "src4"]).then(function(imgs) {
              // all images are loaded now and in the array imgs
              }, function(errImg) {
              // at least one image failed to load
              });





              share|improve this answer


























              • Wow, thanks mate. This is great stuff! 100% !!

                – SquareCat
                Nov 25 '11 at 15:36






              • 2





                For completeness on this function, you could add onerror handlers, onabort handlers and a timeout such that you could still call your callback if one or more of the images had a problem loading and would never complete successfully. It will work fine as is if the images don't have errors loading.

                – jfriend00
                Nov 25 '11 at 15:46













              • Yes, that is quite nice. I was trying to show that, but I fell short.

                – Simon
                Nov 26 '11 at 14:17













              • Added versions of the preloadImages() function that use promises, both standard ES6 promises and jQuery promises.

                – jfriend00
                Nov 9 '15 at 17:43











              • It seems to me that new additions are missing img.src = src; after var img = new Image();

                – Andris Zalitis
                Dec 16 '15 at 7:42
















              28














              Here's a function that will preload images from an array and call your callback when the last one has finished:



              function preloadImages(srcs, imgs, callback) {
              var img;
              var remaining = srcs.length;
              for (var i = 0; i < srcs.length; i++) {
              img = new Image();
              img.onload = function() {
              --remaining;
              if (remaining <= 0) {
              callback();
              }
              };
              img.src = srcs[i];
              imgs.push(img);
              }
              }

              // then to call it, you would use this
              var imageSrcs = ["src1", "src2", "src3", "src4"];
              var images = ;

              preloadImages(imageSrcs, images, myFunction);




              And since we're now in the age of using promises for asynchronous operations, here's a version of the above that uses promises and notifies the caller via an ES6 standard promise:



              function preloadImages(srcs) {
              function loadImage(src) {
              return new Promise(function(resolve, reject) {
              var img = new Image();
              img.onload = function() {
              resolve(img);
              };
              img.onerror = img.onabort = function() {
              reject(src);
              };
              img.src = src;
              });
              }
              var promises = ;
              for (var i = 0; i < srcs.length; i++) {
              promises.push(loadImage(srcs[i]));
              }
              return Promise.all(promises);
              }

              preloadImages(["src1", "src2", "src3", "src4"]).then(function(imgs) {
              // all images are loaded now and in the array imgs
              }, function(errImg) {
              // at least one image failed to load
              });




              And, here's a version using 2015 jQuery promises:



              function preloadImages(srcs) {
              function loadImage(src) {
              return new $.Deferred(function(def) {
              var img = new Image();
              img.onload = function() {
              def.resolve(img);
              };
              img.onerror = img.onabort = function() {
              def.reject(src);
              };
              img.src = src;
              }).promise();
              }
              var promises = ;
              for (var i = 0; i < srcs.length; i++) {
              promises.push(loadImage(srcs[i]));
              }
              return $.when.apply($, promises).then(function() {
              // return results as a simple array rather than as separate arguments
              return Array.prototype.slice.call(arguments);
              });
              }

              preloadImages(["src1", "src2", "src3", "src4"]).then(function(imgs) {
              // all images are loaded now and in the array imgs
              }, function(errImg) {
              // at least one image failed to load
              });





              share|improve this answer


























              • Wow, thanks mate. This is great stuff! 100% !!

                – SquareCat
                Nov 25 '11 at 15:36






              • 2





                For completeness on this function, you could add onerror handlers, onabort handlers and a timeout such that you could still call your callback if one or more of the images had a problem loading and would never complete successfully. It will work fine as is if the images don't have errors loading.

                – jfriend00
                Nov 25 '11 at 15:46













              • Yes, that is quite nice. I was trying to show that, but I fell short.

                – Simon
                Nov 26 '11 at 14:17













              • Added versions of the preloadImages() function that use promises, both standard ES6 promises and jQuery promises.

                – jfriend00
                Nov 9 '15 at 17:43











              • It seems to me that new additions are missing img.src = src; after var img = new Image();

                – Andris Zalitis
                Dec 16 '15 at 7:42














              28












              28








              28







              Here's a function that will preload images from an array and call your callback when the last one has finished:



              function preloadImages(srcs, imgs, callback) {
              var img;
              var remaining = srcs.length;
              for (var i = 0; i < srcs.length; i++) {
              img = new Image();
              img.onload = function() {
              --remaining;
              if (remaining <= 0) {
              callback();
              }
              };
              img.src = srcs[i];
              imgs.push(img);
              }
              }

              // then to call it, you would use this
              var imageSrcs = ["src1", "src2", "src3", "src4"];
              var images = ;

              preloadImages(imageSrcs, images, myFunction);




              And since we're now in the age of using promises for asynchronous operations, here's a version of the above that uses promises and notifies the caller via an ES6 standard promise:



              function preloadImages(srcs) {
              function loadImage(src) {
              return new Promise(function(resolve, reject) {
              var img = new Image();
              img.onload = function() {
              resolve(img);
              };
              img.onerror = img.onabort = function() {
              reject(src);
              };
              img.src = src;
              });
              }
              var promises = ;
              for (var i = 0; i < srcs.length; i++) {
              promises.push(loadImage(srcs[i]));
              }
              return Promise.all(promises);
              }

              preloadImages(["src1", "src2", "src3", "src4"]).then(function(imgs) {
              // all images are loaded now and in the array imgs
              }, function(errImg) {
              // at least one image failed to load
              });




              And, here's a version using 2015 jQuery promises:



              function preloadImages(srcs) {
              function loadImage(src) {
              return new $.Deferred(function(def) {
              var img = new Image();
              img.onload = function() {
              def.resolve(img);
              };
              img.onerror = img.onabort = function() {
              def.reject(src);
              };
              img.src = src;
              }).promise();
              }
              var promises = ;
              for (var i = 0; i < srcs.length; i++) {
              promises.push(loadImage(srcs[i]));
              }
              return $.when.apply($, promises).then(function() {
              // return results as a simple array rather than as separate arguments
              return Array.prototype.slice.call(arguments);
              });
              }

              preloadImages(["src1", "src2", "src3", "src4"]).then(function(imgs) {
              // all images are loaded now and in the array imgs
              }, function(errImg) {
              // at least one image failed to load
              });





              share|improve this answer















              Here's a function that will preload images from an array and call your callback when the last one has finished:



              function preloadImages(srcs, imgs, callback) {
              var img;
              var remaining = srcs.length;
              for (var i = 0; i < srcs.length; i++) {
              img = new Image();
              img.onload = function() {
              --remaining;
              if (remaining <= 0) {
              callback();
              }
              };
              img.src = srcs[i];
              imgs.push(img);
              }
              }

              // then to call it, you would use this
              var imageSrcs = ["src1", "src2", "src3", "src4"];
              var images = ;

              preloadImages(imageSrcs, images, myFunction);




              And since we're now in the age of using promises for asynchronous operations, here's a version of the above that uses promises and notifies the caller via an ES6 standard promise:



              function preloadImages(srcs) {
              function loadImage(src) {
              return new Promise(function(resolve, reject) {
              var img = new Image();
              img.onload = function() {
              resolve(img);
              };
              img.onerror = img.onabort = function() {
              reject(src);
              };
              img.src = src;
              });
              }
              var promises = ;
              for (var i = 0; i < srcs.length; i++) {
              promises.push(loadImage(srcs[i]));
              }
              return Promise.all(promises);
              }

              preloadImages(["src1", "src2", "src3", "src4"]).then(function(imgs) {
              // all images are loaded now and in the array imgs
              }, function(errImg) {
              // at least one image failed to load
              });




              And, here's a version using 2015 jQuery promises:



              function preloadImages(srcs) {
              function loadImage(src) {
              return new $.Deferred(function(def) {
              var img = new Image();
              img.onload = function() {
              def.resolve(img);
              };
              img.onerror = img.onabort = function() {
              def.reject(src);
              };
              img.src = src;
              }).promise();
              }
              var promises = ;
              for (var i = 0; i < srcs.length; i++) {
              promises.push(loadImage(srcs[i]));
              }
              return $.when.apply($, promises).then(function() {
              // return results as a simple array rather than as separate arguments
              return Array.prototype.slice.call(arguments);
              });
              }

              preloadImages(["src1", "src2", "src3", "src4"]).then(function(imgs) {
              // all images are loaded now and in the array imgs
              }, function(errImg) {
              // at least one image failed to load
              });






              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Dec 16 '15 at 15:39

























              answered Nov 25 '11 at 6:03









              jfriend00jfriend00

              429k54550599




              429k54550599













              • Wow, thanks mate. This is great stuff! 100% !!

                – SquareCat
                Nov 25 '11 at 15:36






              • 2





                For completeness on this function, you could add onerror handlers, onabort handlers and a timeout such that you could still call your callback if one or more of the images had a problem loading and would never complete successfully. It will work fine as is if the images don't have errors loading.

                – jfriend00
                Nov 25 '11 at 15:46













              • Yes, that is quite nice. I was trying to show that, but I fell short.

                – Simon
                Nov 26 '11 at 14:17













              • Added versions of the preloadImages() function that use promises, both standard ES6 promises and jQuery promises.

                – jfriend00
                Nov 9 '15 at 17:43











              • It seems to me that new additions are missing img.src = src; after var img = new Image();

                – Andris Zalitis
                Dec 16 '15 at 7:42



















              • Wow, thanks mate. This is great stuff! 100% !!

                – SquareCat
                Nov 25 '11 at 15:36






              • 2





                For completeness on this function, you could add onerror handlers, onabort handlers and a timeout such that you could still call your callback if one or more of the images had a problem loading and would never complete successfully. It will work fine as is if the images don't have errors loading.

                – jfriend00
                Nov 25 '11 at 15:46













              • Yes, that is quite nice. I was trying to show that, but I fell short.

                – Simon
                Nov 26 '11 at 14:17













              • Added versions of the preloadImages() function that use promises, both standard ES6 promises and jQuery promises.

                – jfriend00
                Nov 9 '15 at 17:43











              • It seems to me that new additions are missing img.src = src; after var img = new Image();

                – Andris Zalitis
                Dec 16 '15 at 7:42

















              Wow, thanks mate. This is great stuff! 100% !!

              – SquareCat
              Nov 25 '11 at 15:36





              Wow, thanks mate. This is great stuff! 100% !!

              – SquareCat
              Nov 25 '11 at 15:36




              2




              2





              For completeness on this function, you could add onerror handlers, onabort handlers and a timeout such that you could still call your callback if one or more of the images had a problem loading and would never complete successfully. It will work fine as is if the images don't have errors loading.

              – jfriend00
              Nov 25 '11 at 15:46







              For completeness on this function, you could add onerror handlers, onabort handlers and a timeout such that you could still call your callback if one or more of the images had a problem loading and would never complete successfully. It will work fine as is if the images don't have errors loading.

              – jfriend00
              Nov 25 '11 at 15:46















              Yes, that is quite nice. I was trying to show that, but I fell short.

              – Simon
              Nov 26 '11 at 14:17







              Yes, that is quite nice. I was trying to show that, but I fell short.

              – Simon
              Nov 26 '11 at 14:17















              Added versions of the preloadImages() function that use promises, both standard ES6 promises and jQuery promises.

              – jfriend00
              Nov 9 '15 at 17:43





              Added versions of the preloadImages() function that use promises, both standard ES6 promises and jQuery promises.

              – jfriend00
              Nov 9 '15 at 17:43













              It seems to me that new additions are missing img.src = src; after var img = new Image();

              – Andris Zalitis
              Dec 16 '15 at 7:42





              It seems to me that new additions are missing img.src = src; after var img = new Image();

              – Andris Zalitis
              Dec 16 '15 at 7:42













              2















              For a more robust solution, consider this PRELOADER function with a couple of callbacks (jsFiddle).



              Keeping it simple:



              In this example, I'm passing callbacks and an image hash inside an Object literal PRELOADER_OBJECT, then overriding the callbacks inside PRELOADER:



              // preloder object stores image hash
              // and event handler callbacks
              var PRELOADER_OBJECT = {

              imgArray:"http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg".split(" "),

              progressCallback : function( percent )
              {
              $( '#preloader_progress' ).html( 'preload progress complete : ' + percent + '%' );
              console.log( 'preload progress complete : ', percent );
              },

              completeCallback : function( scope )
              {
              // hide preload indicator, do something when finished
              console.log( 'preload complete!' );
              $( '#preloader_modal' ).delay( 1000 ).animate( { opacity : 0 }, function( )
              {
              $( '.preload_class' ).each( function( index )
              {
              $( this ).delay( index * 100 ).animate( { opacity : 0 } );
              } );
              } );
              }

              /*Localize params and create PRELOADER object.
              Needs to loadImages( ); iterate through hash and
              call onPreloadProgress( ) and onPreloadComplete( )
              each time until finished. If you're still within
              bounds of the image hash, call progressCallback( )
              recursively. When finished, fire onCompleteCallback( )*/

              var PRELOADER = function( object )
              {
              // preloader modal overlay
              this.modal = undefined;

              // progress indicator container
              this.progressIndicator = undefined;

              // image preload progress
              this.progress = undefined;

              // progress callback
              this.progressCallback = undefined;

              // complete callback
              this.completeCallback = undefined;

              // hash to store key : value pairs for image paths
              this.imgArray = undefined;

              // store images in preloadArray
              this.preloadArray = ;

              // initialize and localize our data
              this.initialize = function( )
              {
              // create preload indicator and overlay modal
              this.createPreloaderModal( );

              // image hash
              this.imgArray = object.imgArray;

              // progress callback event handler
              this.progressCallback = object.progressCallback;

              // complete callback event
              this.completeCallback = object.completeCallback;

              // load images
              this.loadImages( );
              };

              this.progressCallback = function( ) {}; // function to override

              this.completeCallback = function( ) {}; // function to override

              // load images into DOM and fire callbacks
              this.loadImages = function( )
              {
              var that = this;

              // iterate through hash and place images into DOM
              $.each( PRELOADER_OBJECT.imgArray, function( index, object )
              {
              this.image = $( "<img/>", { "src" : object, "class": "preload_class" } ).appendTo( 'body' );

              // mark progress and call progressCallback( ) event handler
              that.progress = Math.ceil( ( index / PRELOADER_OBJECT.imgArray.length ) * 100 );
              that.progressCallback( this.progress );

              that.preloadArray.push( this.image );
              } );

              // check for array bounds and call completeCallback( )
              if ( PRELOADER_OBJECT.imgArray.length )
              {
              this.progressCallback( 100 );
              this.completeCallback( this );
              }
              };

              // create modal to display preload data
              this.createPreloaderModal = function( )
              {
              this.modal = $( '<div/>', { 'id' : 'preloader_modal' } ).appendTo( 'body' );
              this.progressIndicator = $( '<h1/>', { 'id' : 'preloader_progress' } ).appendTo( this.modal );
              };
              };

              // trigger event chain when DOM loads
              $( document ).ready( function( )
              {
              // instantiate PRELOADER instance and pass
              // our JSON data model as a parameter
              var preloader = new PRELOADER( PRELOADER_OBJECT );

              // initialize preloader
              preloader.initialize( );
              } );


              };​



              With a site load large enough to require an image preloader, the modal text display could be easily modified to support a data-driven jQuery animation.






              share|improve this answer






























                2















                For a more robust solution, consider this PRELOADER function with a couple of callbacks (jsFiddle).



                Keeping it simple:



                In this example, I'm passing callbacks and an image hash inside an Object literal PRELOADER_OBJECT, then overriding the callbacks inside PRELOADER:



                // preloder object stores image hash
                // and event handler callbacks
                var PRELOADER_OBJECT = {

                imgArray:"http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg".split(" "),

                progressCallback : function( percent )
                {
                $( '#preloader_progress' ).html( 'preload progress complete : ' + percent + '%' );
                console.log( 'preload progress complete : ', percent );
                },

                completeCallback : function( scope )
                {
                // hide preload indicator, do something when finished
                console.log( 'preload complete!' );
                $( '#preloader_modal' ).delay( 1000 ).animate( { opacity : 0 }, function( )
                {
                $( '.preload_class' ).each( function( index )
                {
                $( this ).delay( index * 100 ).animate( { opacity : 0 } );
                } );
                } );
                }

                /*Localize params and create PRELOADER object.
                Needs to loadImages( ); iterate through hash and
                call onPreloadProgress( ) and onPreloadComplete( )
                each time until finished. If you're still within
                bounds of the image hash, call progressCallback( )
                recursively. When finished, fire onCompleteCallback( )*/

                var PRELOADER = function( object )
                {
                // preloader modal overlay
                this.modal = undefined;

                // progress indicator container
                this.progressIndicator = undefined;

                // image preload progress
                this.progress = undefined;

                // progress callback
                this.progressCallback = undefined;

                // complete callback
                this.completeCallback = undefined;

                // hash to store key : value pairs for image paths
                this.imgArray = undefined;

                // store images in preloadArray
                this.preloadArray = ;

                // initialize and localize our data
                this.initialize = function( )
                {
                // create preload indicator and overlay modal
                this.createPreloaderModal( );

                // image hash
                this.imgArray = object.imgArray;

                // progress callback event handler
                this.progressCallback = object.progressCallback;

                // complete callback event
                this.completeCallback = object.completeCallback;

                // load images
                this.loadImages( );
                };

                this.progressCallback = function( ) {}; // function to override

                this.completeCallback = function( ) {}; // function to override

                // load images into DOM and fire callbacks
                this.loadImages = function( )
                {
                var that = this;

                // iterate through hash and place images into DOM
                $.each( PRELOADER_OBJECT.imgArray, function( index, object )
                {
                this.image = $( "<img/>", { "src" : object, "class": "preload_class" } ).appendTo( 'body' );

                // mark progress and call progressCallback( ) event handler
                that.progress = Math.ceil( ( index / PRELOADER_OBJECT.imgArray.length ) * 100 );
                that.progressCallback( this.progress );

                that.preloadArray.push( this.image );
                } );

                // check for array bounds and call completeCallback( )
                if ( PRELOADER_OBJECT.imgArray.length )
                {
                this.progressCallback( 100 );
                this.completeCallback( this );
                }
                };

                // create modal to display preload data
                this.createPreloaderModal = function( )
                {
                this.modal = $( '<div/>', { 'id' : 'preloader_modal' } ).appendTo( 'body' );
                this.progressIndicator = $( '<h1/>', { 'id' : 'preloader_progress' } ).appendTo( this.modal );
                };
                };

                // trigger event chain when DOM loads
                $( document ).ready( function( )
                {
                // instantiate PRELOADER instance and pass
                // our JSON data model as a parameter
                var preloader = new PRELOADER( PRELOADER_OBJECT );

                // initialize preloader
                preloader.initialize( );
                } );


                };​



                With a site load large enough to require an image preloader, the modal text display could be easily modified to support a data-driven jQuery animation.






                share|improve this answer




























                  2












                  2








                  2








                  For a more robust solution, consider this PRELOADER function with a couple of callbacks (jsFiddle).



                  Keeping it simple:



                  In this example, I'm passing callbacks and an image hash inside an Object literal PRELOADER_OBJECT, then overriding the callbacks inside PRELOADER:



                  // preloder object stores image hash
                  // and event handler callbacks
                  var PRELOADER_OBJECT = {

                  imgArray:"http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg".split(" "),

                  progressCallback : function( percent )
                  {
                  $( '#preloader_progress' ).html( 'preload progress complete : ' + percent + '%' );
                  console.log( 'preload progress complete : ', percent );
                  },

                  completeCallback : function( scope )
                  {
                  // hide preload indicator, do something when finished
                  console.log( 'preload complete!' );
                  $( '#preloader_modal' ).delay( 1000 ).animate( { opacity : 0 }, function( )
                  {
                  $( '.preload_class' ).each( function( index )
                  {
                  $( this ).delay( index * 100 ).animate( { opacity : 0 } );
                  } );
                  } );
                  }

                  /*Localize params and create PRELOADER object.
                  Needs to loadImages( ); iterate through hash and
                  call onPreloadProgress( ) and onPreloadComplete( )
                  each time until finished. If you're still within
                  bounds of the image hash, call progressCallback( )
                  recursively. When finished, fire onCompleteCallback( )*/

                  var PRELOADER = function( object )
                  {
                  // preloader modal overlay
                  this.modal = undefined;

                  // progress indicator container
                  this.progressIndicator = undefined;

                  // image preload progress
                  this.progress = undefined;

                  // progress callback
                  this.progressCallback = undefined;

                  // complete callback
                  this.completeCallback = undefined;

                  // hash to store key : value pairs for image paths
                  this.imgArray = undefined;

                  // store images in preloadArray
                  this.preloadArray = ;

                  // initialize and localize our data
                  this.initialize = function( )
                  {
                  // create preload indicator and overlay modal
                  this.createPreloaderModal( );

                  // image hash
                  this.imgArray = object.imgArray;

                  // progress callback event handler
                  this.progressCallback = object.progressCallback;

                  // complete callback event
                  this.completeCallback = object.completeCallback;

                  // load images
                  this.loadImages( );
                  };

                  this.progressCallback = function( ) {}; // function to override

                  this.completeCallback = function( ) {}; // function to override

                  // load images into DOM and fire callbacks
                  this.loadImages = function( )
                  {
                  var that = this;

                  // iterate through hash and place images into DOM
                  $.each( PRELOADER_OBJECT.imgArray, function( index, object )
                  {
                  this.image = $( "<img/>", { "src" : object, "class": "preload_class" } ).appendTo( 'body' );

                  // mark progress and call progressCallback( ) event handler
                  that.progress = Math.ceil( ( index / PRELOADER_OBJECT.imgArray.length ) * 100 );
                  that.progressCallback( this.progress );

                  that.preloadArray.push( this.image );
                  } );

                  // check for array bounds and call completeCallback( )
                  if ( PRELOADER_OBJECT.imgArray.length )
                  {
                  this.progressCallback( 100 );
                  this.completeCallback( this );
                  }
                  };

                  // create modal to display preload data
                  this.createPreloaderModal = function( )
                  {
                  this.modal = $( '<div/>', { 'id' : 'preloader_modal' } ).appendTo( 'body' );
                  this.progressIndicator = $( '<h1/>', { 'id' : 'preloader_progress' } ).appendTo( this.modal );
                  };
                  };

                  // trigger event chain when DOM loads
                  $( document ).ready( function( )
                  {
                  // instantiate PRELOADER instance and pass
                  // our JSON data model as a parameter
                  var preloader = new PRELOADER( PRELOADER_OBJECT );

                  // initialize preloader
                  preloader.initialize( );
                  } );


                  };​



                  With a site load large enough to require an image preloader, the modal text display could be easily modified to support a data-driven jQuery animation.






                  share|improve this answer
















                  For a more robust solution, consider this PRELOADER function with a couple of callbacks (jsFiddle).



                  Keeping it simple:



                  In this example, I'm passing callbacks and an image hash inside an Object literal PRELOADER_OBJECT, then overriding the callbacks inside PRELOADER:



                  // preloder object stores image hash
                  // and event handler callbacks
                  var PRELOADER_OBJECT = {

                  imgArray:"http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg http://torwars.com/wp-content/uploads/2012/02/chewbacca-w-han-solo-anh.jpg".split(" "),

                  progressCallback : function( percent )
                  {
                  $( '#preloader_progress' ).html( 'preload progress complete : ' + percent + '%' );
                  console.log( 'preload progress complete : ', percent );
                  },

                  completeCallback : function( scope )
                  {
                  // hide preload indicator, do something when finished
                  console.log( 'preload complete!' );
                  $( '#preloader_modal' ).delay( 1000 ).animate( { opacity : 0 }, function( )
                  {
                  $( '.preload_class' ).each( function( index )
                  {
                  $( this ).delay( index * 100 ).animate( { opacity : 0 } );
                  } );
                  } );
                  }

                  /*Localize params and create PRELOADER object.
                  Needs to loadImages( ); iterate through hash and
                  call onPreloadProgress( ) and onPreloadComplete( )
                  each time until finished. If you're still within
                  bounds of the image hash, call progressCallback( )
                  recursively. When finished, fire onCompleteCallback( )*/

                  var PRELOADER = function( object )
                  {
                  // preloader modal overlay
                  this.modal = undefined;

                  // progress indicator container
                  this.progressIndicator = undefined;

                  // image preload progress
                  this.progress = undefined;

                  // progress callback
                  this.progressCallback = undefined;

                  // complete callback
                  this.completeCallback = undefined;

                  // hash to store key : value pairs for image paths
                  this.imgArray = undefined;

                  // store images in preloadArray
                  this.preloadArray = ;

                  // initialize and localize our data
                  this.initialize = function( )
                  {
                  // create preload indicator and overlay modal
                  this.createPreloaderModal( );

                  // image hash
                  this.imgArray = object.imgArray;

                  // progress callback event handler
                  this.progressCallback = object.progressCallback;

                  // complete callback event
                  this.completeCallback = object.completeCallback;

                  // load images
                  this.loadImages( );
                  };

                  this.progressCallback = function( ) {}; // function to override

                  this.completeCallback = function( ) {}; // function to override

                  // load images into DOM and fire callbacks
                  this.loadImages = function( )
                  {
                  var that = this;

                  // iterate through hash and place images into DOM
                  $.each( PRELOADER_OBJECT.imgArray, function( index, object )
                  {
                  this.image = $( "<img/>", { "src" : object, "class": "preload_class" } ).appendTo( 'body' );

                  // mark progress and call progressCallback( ) event handler
                  that.progress = Math.ceil( ( index / PRELOADER_OBJECT.imgArray.length ) * 100 );
                  that.progressCallback( this.progress );

                  that.preloadArray.push( this.image );
                  } );

                  // check for array bounds and call completeCallback( )
                  if ( PRELOADER_OBJECT.imgArray.length )
                  {
                  this.progressCallback( 100 );
                  this.completeCallback( this );
                  }
                  };

                  // create modal to display preload data
                  this.createPreloaderModal = function( )
                  {
                  this.modal = $( '<div/>', { 'id' : 'preloader_modal' } ).appendTo( 'body' );
                  this.progressIndicator = $( '<h1/>', { 'id' : 'preloader_progress' } ).appendTo( this.modal );
                  };
                  };

                  // trigger event chain when DOM loads
                  $( document ).ready( function( )
                  {
                  // instantiate PRELOADER instance and pass
                  // our JSON data model as a parameter
                  var preloader = new PRELOADER( PRELOADER_OBJECT );

                  // initialize preloader
                  preloader.initialize( );
                  } );


                  };​



                  With a site load large enough to require an image preloader, the modal text display could be easily modified to support a data-driven jQuery animation.







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Oct 17 '12 at 3:43

























                  answered Oct 14 '12 at 23:13









                  edwerneredwerner

                  3115




                  3115























                      0














                      Preloading and loading are the same thing. You can insert the image (either create a new one or change the "src" attribute of an existing one) but hide the element using $("element").hide() or something similar. Before you do this, attach a load event handler like so:



                      var images = ["src1", "src2", "src3", "src4"];
                      var len = images.length;

                      for(i=0; i<len; i++){
                      $("parent element").html('<img id="new-img" style="display:none;" src="'+images[i]+'"/>');
                      $("new-img").load(function(){
                      //Your image is now "preloaded"

                      //Now you can show the image, or do other stuff
                      $(this).show();
                      });
                      }





                      share|improve this answer


























                      • Thank You, simon. I am trying to set this up for a contact map where there are parts of a country that are to be displayed, which are each PNGs, pretty huge. I want to preload the whole thing, then add a class name to its container to make it visible. That's pretty much all. But attaching a callback for triggering on load of a single image is not what i am looking for.

                        – SquareCat
                        Nov 25 '11 at 3:32











                      • What do you mean by "pre-loading"? I assume you want to load it before the user needs it so that when he/she wants to see it, it doesn't take a millenium to show up. Use the above code to load the image, once it is loaded, you can store a reference to it so you can refer to it when the user needs to see it. This effectively pre-loads the image.

                        – Simon
                        Nov 25 '11 at 3:37











                      • Thank you, i understand, but it is just not what i am looking for. I am trying to find a script that i can feed with an array of image sources, which loads them in the background and then triggers an event.

                        – SquareCat
                        Nov 25 '11 at 3:41











                      • Perhaps my update will help. Otherwise, good luck.

                        – Simon
                        Nov 25 '11 at 3:53











                      • Every time an image is done loading, do a var++, and if the var == the number of images to preload, run your "everything loaded" routine

                        – Thilo Savage
                        Nov 25 '11 at 4:23


















                      0














                      Preloading and loading are the same thing. You can insert the image (either create a new one or change the "src" attribute of an existing one) but hide the element using $("element").hide() or something similar. Before you do this, attach a load event handler like so:



                      var images = ["src1", "src2", "src3", "src4"];
                      var len = images.length;

                      for(i=0; i<len; i++){
                      $("parent element").html('<img id="new-img" style="display:none;" src="'+images[i]+'"/>');
                      $("new-img").load(function(){
                      //Your image is now "preloaded"

                      //Now you can show the image, or do other stuff
                      $(this).show();
                      });
                      }





                      share|improve this answer


























                      • Thank You, simon. I am trying to set this up for a contact map where there are parts of a country that are to be displayed, which are each PNGs, pretty huge. I want to preload the whole thing, then add a class name to its container to make it visible. That's pretty much all. But attaching a callback for triggering on load of a single image is not what i am looking for.

                        – SquareCat
                        Nov 25 '11 at 3:32











                      • What do you mean by "pre-loading"? I assume you want to load it before the user needs it so that when he/she wants to see it, it doesn't take a millenium to show up. Use the above code to load the image, once it is loaded, you can store a reference to it so you can refer to it when the user needs to see it. This effectively pre-loads the image.

                        – Simon
                        Nov 25 '11 at 3:37











                      • Thank you, i understand, but it is just not what i am looking for. I am trying to find a script that i can feed with an array of image sources, which loads them in the background and then triggers an event.

                        – SquareCat
                        Nov 25 '11 at 3:41











                      • Perhaps my update will help. Otherwise, good luck.

                        – Simon
                        Nov 25 '11 at 3:53











                      • Every time an image is done loading, do a var++, and if the var == the number of images to preload, run your "everything loaded" routine

                        – Thilo Savage
                        Nov 25 '11 at 4:23
















                      0












                      0








                      0







                      Preloading and loading are the same thing. You can insert the image (either create a new one or change the "src" attribute of an existing one) but hide the element using $("element").hide() or something similar. Before you do this, attach a load event handler like so:



                      var images = ["src1", "src2", "src3", "src4"];
                      var len = images.length;

                      for(i=0; i<len; i++){
                      $("parent element").html('<img id="new-img" style="display:none;" src="'+images[i]+'"/>');
                      $("new-img").load(function(){
                      //Your image is now "preloaded"

                      //Now you can show the image, or do other stuff
                      $(this).show();
                      });
                      }





                      share|improve this answer















                      Preloading and loading are the same thing. You can insert the image (either create a new one or change the "src" attribute of an existing one) but hide the element using $("element").hide() or something similar. Before you do this, attach a load event handler like so:



                      var images = ["src1", "src2", "src3", "src4"];
                      var len = images.length;

                      for(i=0; i<len; i++){
                      $("parent element").html('<img id="new-img" style="display:none;" src="'+images[i]+'"/>');
                      $("new-img").load(function(){
                      //Your image is now "preloaded"

                      //Now you can show the image, or do other stuff
                      $(this).show();
                      });
                      }






                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited Nov 25 '11 at 3:53

























                      answered Nov 25 '11 at 3:27









                      SimonSimon

                      1,696118




                      1,696118













                      • Thank You, simon. I am trying to set this up for a contact map where there are parts of a country that are to be displayed, which are each PNGs, pretty huge. I want to preload the whole thing, then add a class name to its container to make it visible. That's pretty much all. But attaching a callback for triggering on load of a single image is not what i am looking for.

                        – SquareCat
                        Nov 25 '11 at 3:32











                      • What do you mean by "pre-loading"? I assume you want to load it before the user needs it so that when he/she wants to see it, it doesn't take a millenium to show up. Use the above code to load the image, once it is loaded, you can store a reference to it so you can refer to it when the user needs to see it. This effectively pre-loads the image.

                        – Simon
                        Nov 25 '11 at 3:37











                      • Thank you, i understand, but it is just not what i am looking for. I am trying to find a script that i can feed with an array of image sources, which loads them in the background and then triggers an event.

                        – SquareCat
                        Nov 25 '11 at 3:41











                      • Perhaps my update will help. Otherwise, good luck.

                        – Simon
                        Nov 25 '11 at 3:53











                      • Every time an image is done loading, do a var++, and if the var == the number of images to preload, run your "everything loaded" routine

                        – Thilo Savage
                        Nov 25 '11 at 4:23





















                      • Thank You, simon. I am trying to set this up for a contact map where there are parts of a country that are to be displayed, which are each PNGs, pretty huge. I want to preload the whole thing, then add a class name to its container to make it visible. That's pretty much all. But attaching a callback for triggering on load of a single image is not what i am looking for.

                        – SquareCat
                        Nov 25 '11 at 3:32











                      • What do you mean by "pre-loading"? I assume you want to load it before the user needs it so that when he/she wants to see it, it doesn't take a millenium to show up. Use the above code to load the image, once it is loaded, you can store a reference to it so you can refer to it when the user needs to see it. This effectively pre-loads the image.

                        – Simon
                        Nov 25 '11 at 3:37











                      • Thank you, i understand, but it is just not what i am looking for. I am trying to find a script that i can feed with an array of image sources, which loads them in the background and then triggers an event.

                        – SquareCat
                        Nov 25 '11 at 3:41











                      • Perhaps my update will help. Otherwise, good luck.

                        – Simon
                        Nov 25 '11 at 3:53











                      • Every time an image is done loading, do a var++, and if the var == the number of images to preload, run your "everything loaded" routine

                        – Thilo Savage
                        Nov 25 '11 at 4:23



















                      Thank You, simon. I am trying to set this up for a contact map where there are parts of a country that are to be displayed, which are each PNGs, pretty huge. I want to preload the whole thing, then add a class name to its container to make it visible. That's pretty much all. But attaching a callback for triggering on load of a single image is not what i am looking for.

                      – SquareCat
                      Nov 25 '11 at 3:32





                      Thank You, simon. I am trying to set this up for a contact map where there are parts of a country that are to be displayed, which are each PNGs, pretty huge. I want to preload the whole thing, then add a class name to its container to make it visible. That's pretty much all. But attaching a callback for triggering on load of a single image is not what i am looking for.

                      – SquareCat
                      Nov 25 '11 at 3:32













                      What do you mean by "pre-loading"? I assume you want to load it before the user needs it so that when he/she wants to see it, it doesn't take a millenium to show up. Use the above code to load the image, once it is loaded, you can store a reference to it so you can refer to it when the user needs to see it. This effectively pre-loads the image.

                      – Simon
                      Nov 25 '11 at 3:37





                      What do you mean by "pre-loading"? I assume you want to load it before the user needs it so that when he/she wants to see it, it doesn't take a millenium to show up. Use the above code to load the image, once it is loaded, you can store a reference to it so you can refer to it when the user needs to see it. This effectively pre-loads the image.

                      – Simon
                      Nov 25 '11 at 3:37













                      Thank you, i understand, but it is just not what i am looking for. I am trying to find a script that i can feed with an array of image sources, which loads them in the background and then triggers an event.

                      – SquareCat
                      Nov 25 '11 at 3:41





                      Thank you, i understand, but it is just not what i am looking for. I am trying to find a script that i can feed with an array of image sources, which loads them in the background and then triggers an event.

                      – SquareCat
                      Nov 25 '11 at 3:41













                      Perhaps my update will help. Otherwise, good luck.

                      – Simon
                      Nov 25 '11 at 3:53





                      Perhaps my update will help. Otherwise, good luck.

                      – Simon
                      Nov 25 '11 at 3:53













                      Every time an image is done loading, do a var++, and if the var == the number of images to preload, run your "everything loaded" routine

                      – Thilo Savage
                      Nov 25 '11 at 4:23







                      Every time an image is done loading, do a var++, and if the var == the number of images to preload, run your "everything loaded" routine

                      – Thilo Savage
                      Nov 25 '11 at 4:23













                      0














                      Preloading takes some extra work like creating new image elements, monitoring if they are all loaded and then replacing them with the existing ones in the DOM. However you may do this directly on the DOM <img> elements indefinitely many times without replacing them.



                      We may use the Fetch API to access the images, wait until they are all downloaded within a promise.all() and then in one go just replace the src attributes of the img elements at the most suitable time by using window.requestAnimationFrame().



                      In the following example I refresh the src attributes of the img elements 10 times. As per the delay, i am using the the time it takes up to load 4 images from an API. So once we have all images loaded i am immediately placing a new request by calling the same refreshImagesNTimes function recursively.



                      You may of course chose to load as many image blobs as you like all at once and display them in groups in precise time intervals by using a simple setTimeout mechanism.






                      function refreshImagesNTimes(nodeList,count = -1){
                      var imgPromises = Array.from({length: nodeList.length})
                      .map(_ => fetch("https://unsplash.it/480/640/?random").then(res => res.blob()));
                      Promise.all(imgPromises)
                      .then(function(blobs){
                      window.requestAnimationFrame(_ => nodeList.forEach((img, i) => img.src = (window.URL || window.webkitURL).createObjectURL(blobs[i])));
                      --count && refreshImagesNTimes(nodeList, count);
                      });
                      }

                      var images = document.querySelectorAll("#container img");
                      refreshImagesNTimes(images,10);

                      #container {
                      display: flex;
                      flex-wrap: wrap;
                      justify-content: space-evenly;
                      align-items: center;
                      margin: auto;
                      width: 75vw;
                      height: 56.25vw;
                      background-color: #000;
                      box-sizing: border-box;
                      }

                      img {
                      width: 45%;
                      height: 45%;
                      background-color: thistle;
                      }

                      <div id="container">
                      <img>
                      <img>
                      <img>
                      <img>
                      </div>








                      share|improve this answer






























                        0














                        Preloading takes some extra work like creating new image elements, monitoring if they are all loaded and then replacing them with the existing ones in the DOM. However you may do this directly on the DOM <img> elements indefinitely many times without replacing them.



                        We may use the Fetch API to access the images, wait until they are all downloaded within a promise.all() and then in one go just replace the src attributes of the img elements at the most suitable time by using window.requestAnimationFrame().



                        In the following example I refresh the src attributes of the img elements 10 times. As per the delay, i am using the the time it takes up to load 4 images from an API. So once we have all images loaded i am immediately placing a new request by calling the same refreshImagesNTimes function recursively.



                        You may of course chose to load as many image blobs as you like all at once and display them in groups in precise time intervals by using a simple setTimeout mechanism.






                        function refreshImagesNTimes(nodeList,count = -1){
                        var imgPromises = Array.from({length: nodeList.length})
                        .map(_ => fetch("https://unsplash.it/480/640/?random").then(res => res.blob()));
                        Promise.all(imgPromises)
                        .then(function(blobs){
                        window.requestAnimationFrame(_ => nodeList.forEach((img, i) => img.src = (window.URL || window.webkitURL).createObjectURL(blobs[i])));
                        --count && refreshImagesNTimes(nodeList, count);
                        });
                        }

                        var images = document.querySelectorAll("#container img");
                        refreshImagesNTimes(images,10);

                        #container {
                        display: flex;
                        flex-wrap: wrap;
                        justify-content: space-evenly;
                        align-items: center;
                        margin: auto;
                        width: 75vw;
                        height: 56.25vw;
                        background-color: #000;
                        box-sizing: border-box;
                        }

                        img {
                        width: 45%;
                        height: 45%;
                        background-color: thistle;
                        }

                        <div id="container">
                        <img>
                        <img>
                        <img>
                        <img>
                        </div>








                        share|improve this answer




























                          0












                          0








                          0







                          Preloading takes some extra work like creating new image elements, monitoring if they are all loaded and then replacing them with the existing ones in the DOM. However you may do this directly on the DOM <img> elements indefinitely many times without replacing them.



                          We may use the Fetch API to access the images, wait until they are all downloaded within a promise.all() and then in one go just replace the src attributes of the img elements at the most suitable time by using window.requestAnimationFrame().



                          In the following example I refresh the src attributes of the img elements 10 times. As per the delay, i am using the the time it takes up to load 4 images from an API. So once we have all images loaded i am immediately placing a new request by calling the same refreshImagesNTimes function recursively.



                          You may of course chose to load as many image blobs as you like all at once and display them in groups in precise time intervals by using a simple setTimeout mechanism.






                          function refreshImagesNTimes(nodeList,count = -1){
                          var imgPromises = Array.from({length: nodeList.length})
                          .map(_ => fetch("https://unsplash.it/480/640/?random").then(res => res.blob()));
                          Promise.all(imgPromises)
                          .then(function(blobs){
                          window.requestAnimationFrame(_ => nodeList.forEach((img, i) => img.src = (window.URL || window.webkitURL).createObjectURL(blobs[i])));
                          --count && refreshImagesNTimes(nodeList, count);
                          });
                          }

                          var images = document.querySelectorAll("#container img");
                          refreshImagesNTimes(images,10);

                          #container {
                          display: flex;
                          flex-wrap: wrap;
                          justify-content: space-evenly;
                          align-items: center;
                          margin: auto;
                          width: 75vw;
                          height: 56.25vw;
                          background-color: #000;
                          box-sizing: border-box;
                          }

                          img {
                          width: 45%;
                          height: 45%;
                          background-color: thistle;
                          }

                          <div id="container">
                          <img>
                          <img>
                          <img>
                          <img>
                          </div>








                          share|improve this answer















                          Preloading takes some extra work like creating new image elements, monitoring if they are all loaded and then replacing them with the existing ones in the DOM. However you may do this directly on the DOM <img> elements indefinitely many times without replacing them.



                          We may use the Fetch API to access the images, wait until they are all downloaded within a promise.all() and then in one go just replace the src attributes of the img elements at the most suitable time by using window.requestAnimationFrame().



                          In the following example I refresh the src attributes of the img elements 10 times. As per the delay, i am using the the time it takes up to load 4 images from an API. So once we have all images loaded i am immediately placing a new request by calling the same refreshImagesNTimes function recursively.



                          You may of course chose to load as many image blobs as you like all at once and display them in groups in precise time intervals by using a simple setTimeout mechanism.






                          function refreshImagesNTimes(nodeList,count = -1){
                          var imgPromises = Array.from({length: nodeList.length})
                          .map(_ => fetch("https://unsplash.it/480/640/?random").then(res => res.blob()));
                          Promise.all(imgPromises)
                          .then(function(blobs){
                          window.requestAnimationFrame(_ => nodeList.forEach((img, i) => img.src = (window.URL || window.webkitURL).createObjectURL(blobs[i])));
                          --count && refreshImagesNTimes(nodeList, count);
                          });
                          }

                          var images = document.querySelectorAll("#container img");
                          refreshImagesNTimes(images,10);

                          #container {
                          display: flex;
                          flex-wrap: wrap;
                          justify-content: space-evenly;
                          align-items: center;
                          margin: auto;
                          width: 75vw;
                          height: 56.25vw;
                          background-color: #000;
                          box-sizing: border-box;
                          }

                          img {
                          width: 45%;
                          height: 45%;
                          background-color: thistle;
                          }

                          <div id="container">
                          <img>
                          <img>
                          <img>
                          <img>
                          </div>








                          function refreshImagesNTimes(nodeList,count = -1){
                          var imgPromises = Array.from({length: nodeList.length})
                          .map(_ => fetch("https://unsplash.it/480/640/?random").then(res => res.blob()));
                          Promise.all(imgPromises)
                          .then(function(blobs){
                          window.requestAnimationFrame(_ => nodeList.forEach((img, i) => img.src = (window.URL || window.webkitURL).createObjectURL(blobs[i])));
                          --count && refreshImagesNTimes(nodeList, count);
                          });
                          }

                          var images = document.querySelectorAll("#container img");
                          refreshImagesNTimes(images,10);

                          #container {
                          display: flex;
                          flex-wrap: wrap;
                          justify-content: space-evenly;
                          align-items: center;
                          margin: auto;
                          width: 75vw;
                          height: 56.25vw;
                          background-color: #000;
                          box-sizing: border-box;
                          }

                          img {
                          width: 45%;
                          height: 45%;
                          background-color: thistle;
                          }

                          <div id="container">
                          <img>
                          <img>
                          <img>
                          <img>
                          </div>





                          function refreshImagesNTimes(nodeList,count = -1){
                          var imgPromises = Array.from({length: nodeList.length})
                          .map(_ => fetch("https://unsplash.it/480/640/?random").then(res => res.blob()));
                          Promise.all(imgPromises)
                          .then(function(blobs){
                          window.requestAnimationFrame(_ => nodeList.forEach((img, i) => img.src = (window.URL || window.webkitURL).createObjectURL(blobs[i])));
                          --count && refreshImagesNTimes(nodeList, count);
                          });
                          }

                          var images = document.querySelectorAll("#container img");
                          refreshImagesNTimes(images,10);

                          #container {
                          display: flex;
                          flex-wrap: wrap;
                          justify-content: space-evenly;
                          align-items: center;
                          margin: auto;
                          width: 75vw;
                          height: 56.25vw;
                          background-color: #000;
                          box-sizing: border-box;
                          }

                          img {
                          width: 45%;
                          height: 45%;
                          background-color: thistle;
                          }

                          <div id="container">
                          <img>
                          <img>
                          <img>
                          <img>
                          </div>






                          share|improve this answer














                          share|improve this answer



                          share|improve this answer








                          edited Sep 10 '17 at 12:24

























                          answered Sep 10 '17 at 9:24









                          ReduRedu

                          12.7k22435




                          12.7k22435






























                              draft saved

                              draft discarded




















































                              Thanks for contributing an answer to Stack Overflow!


                              • Please be sure to answer the question. Provide details and share your research!

                              But avoid



                              • Asking for help, clarification, or responding to other answers.

                              • Making statements based on opinion; back them up with references or personal experience.


                              To learn more, see our tips on writing great answers.




                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function () {
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f8264528%2fimage-preloader-javascript-that-supports-events%23new-answer', 'question_page');
                              }
                              );

                              Post as a guest















                              Required, but never shown





















































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown

































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown







                              Popular posts from this blog

                              Berounka

                              Sphinx de Gizeh

                              Different font size/position of beamer's navigation symbols template's content depending on regular/plain...