123

Pen Settings

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

You're using npm packages, so we've auto-selected Babel for you here, which we require to process imports and make it all work. If you need to use a different JavaScript preprocessor, remove the packages in the npm tab.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Use npm Packages

We can make npm packages available for you to use in your JavaScript. We use webpack to prepare them and make them available to import. We'll also process your JavaScript with Babel.

⚠️ This feature can only be used by logged in users.

Code Indentation

     

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

HTML Settings

Here you can Sed posuere consectetur est at lobortis. Donec ullamcorper nulla non metus auctor fringilla. Maecenas sed diam eget risus varius blandit sit amet non magna. Donec id elit non mi porta gravida at eget metus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.

            
              
<div class="deck" data-images='["http://lorempixel.com/1920/1920/city/1","http://lorempixel.com/1920/1920/city/2","http://lorempixel.com/1920/1920/city/3","http://lorempixel.com/1920/1920/city/4","http://lorempixel.com/1920/1920/city/5","http://lorempixel.com/1920/1920/city/6","http://lorempixel.com/1920/1920/city/7","http://lorempixel.com/1920/1920/city/8","http://lorempixel.com/1920/1920/city/9","http://lorempixel.com/1920/1920/city/10","http://lorempixel.com/1920/1920/fashion/1","http://lorempixel.com/1920/1920/fashion/2","http://lorempixel.com/1920/1920/fashion/3","http://lorempixel.com/1920/1920/fashion/4","http://lorempixel.com/1920/1920/fashion/5","http://lorempixel.com/1920/1920/fashion/6","http://lorempixel.com/1920/1920/fashion/7","http://lorempixel.com/1920/1920/fashion/8","http://lorempixel.com/1920/1920/fashion/9","http://lorempixel.com/1920/1920/fashion/10","http://lorempixel.com/1920/1920/technics/1","http://lorempixel.com/1920/1920/technics/2","http://lorempixel.com/1920/1920/technics/3","http://lorempixel.com/1920/1920/technics/4","http://lorempixel.com/1920/1920/technics/5","http://lorempixel.com/1920/1920/technics/6","http://lorempixel.com/1920/1920/technics/7","http://lorempixel.com/1920/1920/technics/8","http://lorempixel.com/1920/1920/technics/9","http://lorempixel.com/1920/1920/technics/10"]'>30 images</div>
<div class="deck" data-images='["http://lorempixel.com/1920/1920/sports/1","http://lorempixel.com/1920/1920/sports/2","http://lorempixel.com/1920/1920/sports/3"]'>3 images</div>
<div class="deck" data-images='["http://lorempixel.com/1920/1920/cats/1","http://lorempixel.com/1920/1920/cats/2","http://lorempixel.com/1920/1920/cats/3","http://lorempixel.com/1920/1920/cats/4","http://lorempixel.com/1920/1920/cats/5","http://lorempixel.com/1920/1920/cats/6","http://lorempixel.com/1920/1920/cats/7","http://lorempixel.com/1920/1920/cats/8","http://lorempixel.com/1920/1920/cats/9","http://lorempixel.com/1920/1920/cats/10"]'>10 images</div>

<h1>Demo: dynamically prefetching images from image decks in parallel.</h1>

<p>Each “deck” has its own list of images, stored in a data attribute (here <code>data-images</code>). The idea is to prefetch the images, and be able to know on a deck basis when it's done. At this point, we can execute any piece of code: adding a class, logging something, launching an image sequence, whatever.</p>

<p>The difficulty is that <strong>we don't want to preload decks in sequence but in parallel</strong>. In other words, we don't want to preload all images from first deck, then all images from second deck, and so on...</p>

<p>Indeed, loading decks in sequence is not ideal because in the scenario where the first deck has a ton of images (here <code>30</code>), and the second one has very few of them (here <code>3</code>), then the second deck would have to wait until the first deck is fully loaded to proceed (whatever code).</p> 

<p>So the idea is to load the first image of all decks, then the second image of all decks, then the third image of all decks and so on until all decks are fully loaded. When a deck is loaded, it emits an event with the id of the deck, which can be listened to.</p>

            
          
!
            
              .deck {
  margin: 10px;
  width: 100px;
  height: 100px;
  padding: 10px;
  background: tomato;
  float: left;
  text-align: center;
  line-height: 100px;
}

.deck.loaded {
  background: lightgreen;
}

body {
  padding: 20px;
  font-size: 115%;
  line-height: 1.45;
}

h1 {
  font-size: 1em;
  clear: both;
}

code {
  color: darkblue;
}
            
          
!
            
              (function (global) {

  'use strict';

  function defer() {
    var resolve, reject, promise = new Promise(function (a, b) {
      resolve = a;
      reject = b;
    });

    return {
      resolve: resolve,
      reject: reject,
      promise: promise
    };
  }

  /**
   * Image preloader
   * @param {Object} options
   */
  var ImagePreloader = function (options) {
    this.options = options || {};
    this.options.parallel = this.options.parallel || false;
    this.items = [];
    this.max = 0;
  };

  /**
   * The `queue` methods is intended to add an array (a deck) of images to the
   * queue. It does not preload the images though; only adds them to the queue.
   * @param  {Array} array - Array of images to add the queue
   * @return {Promise}
   */
  ImagePreloader.prototype.queue = function (array) {
    if (!Array.isArray(array)) {
      array = [array];
    }

    if (array.length > this.max) {
      this.max = array.length;
    }
    
    var deferred = defer();

    this.items.push({
      collection: array,
      deferred: deferred
    });
    
    return deferred.promise;
  };

  /**
   * The `preloadImage` preloads the image resource living at `path` and returns
   * a promise that resolves when the image is successfully loaded by the 
   * browser or if there is an error. Beware, the promise is not rejected in 
   * case the image cannot be loaded; it gets resolved nevertheless.
   * @param  {String} path - Image url
   * @return {Promise}
   */
  ImagePreloader.prototype.preloadImage = function (path) {
    return new Promise(function (resolve, reject) {
      var image = new Image();
      image.onload = resolve;
      image.onerror = resolve;
      image.src = path;
    });
  };

  /**
   * The `preload` method preloads the whole queue of decks added through the
   * `queue` method. It returns a promise that gets resolved when all decks have
   * been fully loaded.
   * The decks are loaded either sequencially (one after the other) or in
   * parallel, depending on the `parallel` options.
   * @return {Promise}
   */
  ImagePreloader.prototype.preload = function () {
    var deck, decks = [];

    if (this.options.parallel) {

      for (var i = 0; i < this.max; i++) {
        this.items.forEach(function (item) {
          if (typeof item.collection[i] !== 'undefined') {
            item.collection[i] = this.preloadImage(item.collection[i]);
          }
        }, this);
      }

    } else {

      this.items.forEach(function (item) {
        item.collection = item.collection.map(this.preloadImage);
      }, this);

    }

    this.items.forEach(function (item) {
      deck = Promise.all(item.collection)
        .then(item.deferred.resolve.bind(item.deferred))
        .catch(console.log.bind(console));

      decks.push(deck);
    });

    return Promise.all(decks);
  };

  global.ImagePreloader = ImagePreloader;

}(window));

function Deck(node, preloader, index) {
    var data = JSON.parse(node.getAttribute('data-images'));

    preloader.queue(data)
        .then(function () {
          console.log('Deck ' + index + ' loaded.');
          node.classList.add('loaded');
        })
    .catch(console.error.bind(console));
}

document.addEventListener('DOMContentLoaded', function () {
var ip = new ImagePreloader({
  parallel: false
});
  var decks = Array.prototype.slice.call(document.querySelectorAll('.deck'));
  
  decks.forEach(function (deck, index) {
    new Deck(deck, ip, index);
  });

  ip.preload()
    .then(function () {
      console.log('All decks loaded.');
    });
});
            
          
!
999px
🕑 One or more of the npm packages you are using needs to be built. You're the first person to ever need it! We're building it right now and your preview will start updating again when it's ready.

Console