본문 바로가기
✘✘✘ 개발일기

[메모] lazy loading with intersectionObserver, 로더, localstorage

by PrettyLog 2022. 10. 10.
const loadLazyImages = (entries, observer) => {
    entries.forEach(function (entry) {
        if (entry.isIntersecting) {
            console.log('loadLazyImages', entry.target.dataset.src, 'fetch data');

            let lazyImage = entry.target;
            lazyImage.src = lazyImage.dataset.src;
            // lazyImage.srcset = lazyImage.dataset.srcset;
            lazyImage.classList.remove('lazy');
            observer.unobserve(lazyImage);
        }
    });
    console.log('entries', entries, observer);
};

const lazyOptions = {
    threshold: 1,
    trackVisibility: true,
    delay: 200,
};

let lazyImageObserver = new IntersectionObserver(loadLazyImages, lazyOptions);

const registerImagesToLazyObserver = (lazyImages, lazyImageObserver) => {
    lazyImages.forEach(function (lazyImage) {
        lazyImageObserver.observe(lazyImage);
    });
};
window.cats.lazyImageObserver = lazyImageObserver;
window.cats.registerImagesToLazyObserver = registerImagesToLazyObserver;
  • localStorage

      window.Storage.prototype.setObj = function (key, obj) {
          return this.setItem(key, JSON.stringify(obj));
      };
      window.Storage.prototype.getObj = function (key) {
          return JSON.parse(this.getItem(key));
      };
    
      const setObjtoLocal = (k, v) => {
          return window.localStorage.setObj(k, v);
      };
    
      const getObjfromLocal = (k, v) => {
          return window.localStorage.getObj(k, v);
      };
  • loader

    class Loader {
      $loader = null;
      data = {
          visible: false,
      };
    
      constructor({ $target, data, setLoading }) {
          this.$loader = document.createElement('section');
          $target.appendChild(this.$loader);
          this.data = data;
          this.setLoading = setLoading;
    
          this.render();
          this.$loader.onclick = () => this.toggleLoader(false);
          console.log('[CREATED]', 'LOADER', this.isLoading);
      }
    
      setState(nextData) {
          this.data = nextData;
          this.render();
          console.log('[UPDATE]', 'Loading', nextData);
      }
    
      toggleLoader(visible) {
          this.setState({ visible });
      }
    
      render() {
          const { visible = false } = this.data;
          if (visible) {
              this.$loader.innerHTML = `
                  <div class="loader-wrapper"> 
                      <div class="loader"></div>
                  </div>
              `;
          } else {
              this.$loader.innerHTML = '';
          }
      }
    }

댓글