foundation.util.imageLoader.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. 'use strict';
  2. import $ from 'jquery';
  3. /**
  4. * Runs a callback function when images are fully loaded.
  5. * @param {Object} images - Image(s) to check if loaded.
  6. * @param {Func} callback - Function to execute when image is fully loaded.
  7. */
  8. function onImagesLoaded(images, callback){
  9. var self = this,
  10. unloaded = images.length;
  11. if (unloaded === 0) {
  12. callback();
  13. }
  14. images.each(function(){
  15. // Check if image is loaded
  16. if (this.complete && typeof this.naturalWidth !== 'undefined') {
  17. singleImageLoaded();
  18. }
  19. else {
  20. // If the above check failed, simulate loading on detached element.
  21. var image = new Image();
  22. // Still count image as loaded if it finalizes with an error.
  23. var events = "load.zf.images error.zf.images";
  24. $(image).one(events, function me(event){
  25. // Unbind the event listeners. We're using 'one' but only one of the two events will have fired.
  26. $(this).off(events, me);
  27. singleImageLoaded();
  28. });
  29. image.src = $(this).attr('src');
  30. }
  31. });
  32. function singleImageLoaded() {
  33. unloaded--;
  34. if (unloaded === 0) {
  35. callback();
  36. }
  37. }
  38. }
  39. export { onImagesLoaded };