JSFiddle - React, Tailwind, and code Playground

by Ben Watts

JavaScript

(function() {
  var resourceCache = {};
  var loading = [];
  var readyCallbacks = [];

  // Load an image url or an array of image urls
  function load(urlOrArr) {
    if (urlOrArr instanceof Array) {
      urlOrArr.forEach(function(url) {
        _load(url);
      });
    } else {
      _load(urlOrArr);
    }
  }

  function _load(url) {
    if (resourceCache[url]) {
      return resourceCache[url];
    } else {
    
      // Create a new img variable
      var img = new Image();
      img.onload = function() {
        // Store the new image object
        resourceCache[url] = img;
				
        // Check to see if all images are loaded
        if (isReady()) {
          // Calls all the callbacks in the array
          readyCallbacks.forEach(function(func) {
            func();
          });
        }
      };
      
      resourceCache[url] = false;
      
      // Start the image loading
      img.src = url;
    }
  }

  function get(url) {
    return resourceCache[url];
  }

  function isReady() {
    var ready = true;
    // For each image inside of resourceCache
    for (var k in resourceCache) {
    // See if any of the images is not an image
    // resourceCache.hasOwnProperty(k) will always return true
      if (/*resourceCache.hasOwnProperty(k) &&*/
        !resourceCache[k]) {
        ready = false;
      }
    }
    return ready;
  }

  function onReady(func) {
    readyCallbacks.push(func);
  }

  window.resources = {
    load: load,
    get: get,
    onReady: onReady,
    isReady: isReady
  };
})();