IntersectionObserver延迟加载无法正常工作

时间:2019-12-10 19:37:48

标签: javascript html css frontend intersection-observer

这是我第一次尝试延迟加载,我想使用IntersectionObserver。首先关注this网站。老实说,我只希望页面的内容等待加载,直到它小于视口下方视口宽度的50%。我不确定如何观察所有内容,所以我只选择了要显示的小部件的类,因为它们是主要内容。不幸的是,我的代码似乎没有做太多事情。我在开始时添加了console.log,以确保正确链接了文件,并且尝试添加更多的console.log来记录窗口小部件移入和移出捕获区域时的情况。第一个console.log有效,但是没有其他反应。

这里是我所拥有的:

console.log('file loaded');
const widgets = document.querySelectorAll('.widget');
const config = {
  root: null,
  rootMargin: '-50px 0px -55% 0px',
  threshold: .5
};

let isLeaving = false;
let observer = new IntersectionObserver(function(entries, self) {
  entries.forEach(entry => {
    if (entry.isIntersecting) {
      // we are ENTERING the "capturing frame". Set the flag.
      isLeaving = true;
      // Do something with entering entry
      console.log("Widget loaded.");
      self.unobserve(entry.target);
    } else if (isLeaving) {
      // we are EXITING the "capturing frame"
      isLeaving = false;
      // Do something with exiting entry
      console.log("Widget is exiting.")

    }
});
}, config);

widgets.forEach(widget => {
  observer.observe(widget);
});

此代码位于其自己的js文件中。我应该在HTML文件中的哪里链接它? 我将不胜感激!让我知道是否需要提供更多信息。

0 个答案:

没有答案