jquery.unveil.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /**
  2. * jQuery Unveil
  3. * A very lightweight jQuery plugin to lazy load images
  4. * inspired from http://luis-almeida.github.com/unveil (2013 Luís Almeida)
  5. *
  6. * Copyright (c) 2017 Mario Stephan <mstephan@shared-files.de>
  7. * Under MIT License (http://www.opensource.org/licenses/mit-license.php)
  8. * https://github.com/knowthelist/fhem-tablet-ui
  9. */
  10. ;(function($) {
  11. $.fn.unveil = function (options) {
  12. var opts = $.extend({}, $.fn.unveil.defaults, options);
  13. var loaded,
  14. images = this;
  15. this.one("unveil", function () {
  16. //console.log('unveil');
  17. var elem = $(this).find('[' + opts.attrib + ']');
  18. var source = elem.attr(opts.attrib);
  19. if (source) {
  20. elem.attr("src", source);
  21. if (typeof opts.afterUnveil === "function") opts.afterUnveil.call(this);
  22. }
  23. });
  24. function unveil() {
  25. var inview = images.filter(function () {
  26. var elem = $(this);
  27. if (elem.is(":hidden")) return;
  28. var viewTop = opts.container.scrollTop(),
  29. viewBottom = viewTop + opts.container.height(),
  30. elemTop = elem.position().top,
  31. elemBottom = elemTop + elem.height();
  32. //console.log(elemTop,elemBottom ,viewTop - opts.threshold, viewBottom + opts.threshold);
  33. return elemBottom >= viewTop - opts.threshold && elemTop <= viewBottom + opts.threshold;
  34. });
  35. loaded = inview.trigger("unveil");
  36. images = images.not(loaded);
  37. }
  38. opts.container.on("scroll.unveil resize.unveil", unveil);
  39. $(document).on(opts.customEvent, unveil);
  40. unveil();
  41. return this;
  42. };
  43. // Plugin defaults
  44. $.fn.unveil.defaults = {
  45. container: $(window),
  46. threshold: 0,
  47. attrib: "data-src",
  48. };
  49. })(window.jQuery);