lazy-container.mjs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import { remove } from "./util.mjs";
  2. const defaultOptions = {
  3. selector: "img"
  4. };
  5. class LazyContainer {
  6. constructor({ el, binding, vnode, lazy }) {
  7. this.el = null;
  8. this.vnode = vnode;
  9. this.binding = binding;
  10. this.options = {};
  11. this.lazy = lazy;
  12. this.queue = [];
  13. this.update({ el, binding });
  14. }
  15. update({ el, binding }) {
  16. this.el = el;
  17. this.options = Object.assign({}, defaultOptions, binding.value);
  18. const imgs = this.getImgs();
  19. imgs.forEach((el2) => {
  20. this.lazy.add(
  21. el2,
  22. Object.assign({}, this.binding, {
  23. value: {
  24. src: "dataset" in el2 ? el2.dataset.src : el2.getAttribute("data-src"),
  25. error: ("dataset" in el2 ? el2.dataset.error : el2.getAttribute("data-error")) || this.options.error,
  26. loading: ("dataset" in el2 ? el2.dataset.loading : el2.getAttribute("data-loading")) || this.options.loading
  27. }
  28. }),
  29. this.vnode
  30. );
  31. });
  32. }
  33. getImgs() {
  34. return Array.from(this.el.querySelectorAll(this.options.selector));
  35. }
  36. clear() {
  37. const imgs = this.getImgs();
  38. imgs.forEach((el) => this.lazy.remove(el));
  39. this.vnode = null;
  40. this.binding = null;
  41. this.lazy = null;
  42. }
  43. }
  44. class LazyContainerManager {
  45. constructor({ lazy }) {
  46. this.lazy = lazy;
  47. this.queue = [];
  48. }
  49. bind(el, binding, vnode) {
  50. const container = new LazyContainer({
  51. el,
  52. binding,
  53. vnode,
  54. lazy: this.lazy
  55. });
  56. this.queue.push(container);
  57. }
  58. update(el, binding, vnode) {
  59. const container = this.queue.find((item) => item.el === el);
  60. if (!container)
  61. return;
  62. container.update({ el, binding, vnode });
  63. }
  64. unbind(el) {
  65. const container = this.queue.find((item) => item.el === el);
  66. if (!container)
  67. return;
  68. container.clear();
  69. remove(this.queue, container);
  70. }
  71. }
  72. export {
  73. LazyContainerManager as default
  74. };