当前位置:首页 > JavaScript

js实现加载更多内容

2026-04-04 07:07:32JavaScript

实现滚动加载更多内容

滚动加载是一种常见的分页加载方式,通过监听滚动事件判断是否到达页面底部触发加载。

window.addEventListener('scroll', function() {
  if (window.innerHeight + window.scrollY >= document.body.offsetHeight - 100) {
    loadMoreContent();
  }
});

function loadMoreContent() {
  // 防止重复加载
  if (isLoading) return;

  isLoading = true;
  fetch('/api/items?page=' + currentPage)
    .then(response => response.json())
    .then(data => {
      currentPage++;
      renderItems(data);
      isLoading = false;
    });
}

使用Intersection Observer API

现代浏览器推荐使用Intersection Observer API实现懒加载,性能优于滚动事件监听。

const observer = new IntersectionObserver((entries) => {
  if (entries[0].isIntersecting) {
    loadMoreContent();
  }
});

// 观察页面底部元素
const sentinel = document.querySelector('#load-more-sentinel');
observer.observe(sentinel);

function loadMoreContent() {
  fetch('/api/items?page=' + currentPage)
    .then(response => response.json())
    .then(data => {
      if (data.length === 0) {
        observer.unobserve(sentinel);
        return;
      }
      currentPage++;
      renderItems(data);
    });
}

按钮点击加载更多

通过用户主动点击按钮触发内容加载,适合需要明确用户意图的场景。

<button id="load-more-btn">加载更多</button>
<div id="content-container"></div>
document.getElementById('load-more-btn').addEventListener('click', loadMoreContent);

function loadMoreContent() {
  fetch('/api/items?page=' + currentPage)
    .then(response => response.json())
    .then(data => {
      if (data.length === 0) {
        document.getElementById('load-more-btn').disabled = true;
        return;
      }
      currentPage++;
      renderItems(data);
    });
}

实现无限滚动列表

对于大型列表,可以使用虚拟滚动技术优化性能,仅渲染可视区域内的元素。

class InfiniteScroll {
  constructor(container, itemHeight, renderItem) {
    this.container = container;
    this.itemHeight = itemHeight;
    this.renderItem = renderItem;
    this.data = [];
    this.visibleItems = [];
    this.startIndex = 0;

    this.init();
  }

  init() {
    this.container.style.height = `${window.innerHeight}px`;
    this.container.style.overflow = 'auto';

    this.container.addEventListener('scroll', () => {
      this.handleScroll();
    });

    this.loadData();
  }

  handleScroll() {
    const scrollTop = this.container.scrollTop;
    const newStartIndex = Math.floor(scrollTop / this.itemHeight);

    if (newStartIndex !== this.startIndex) {
      this.startIndex = newStartIndex;
      this.renderVisibleItems();
    }
  }

  renderVisibleItems() {
    // 仅渲染可视区域内的元素
  }

  loadData() {
    // 获取新数据并更新列表
  }
}

性能优化建议

实现加载更多功能时需注意性能优化,避免不必要的渲染和请求。

js实现加载更多内容

  • 使用防抖函数限制滚动事件触发频率
  • 添加加载状态指示器避免重复请求
  • 实现数据缓存减少服务器请求
  • 对于大量数据考虑虚拟滚动技术
  • 添加错误处理机制应对网络问题
// 防抖函数示例
function debounce(func, delay) {
  let timeout;
  return function() {
    clearTimeout(timeout);
    timeout = setTimeout(() => func.apply(this, arguments), delay);
  };
}

window.addEventListener('scroll', debounce(() => {
  if (window.innerHeight + window.scrollY >= document.body.offsetHeight - 100) {
    loadMoreContent();
  }
}, 200));

标签: 加载更多
分享给朋友:

相关文章

vue实现加载

vue实现加载

Vue 实现加载功能的方法 使用 v-if 或 v-show 控制加载状态 在模板中通过 v-if 或 v-show 控制加载动画的显示与隐藏。v-if 会完全移除 DOM 元素,而 v-show 仅…

vue实现页面加载

vue实现页面加载

Vue 实现页面加载的方法 在 Vue 中实现页面加载效果可以通过多种方式完成,以下是几种常见的方法: 使用 v-if 或 v-show 控制加载状态 通过绑定一个布尔值来控制加载动画的显示与隐藏。…

vue实现图片预加载

vue实现图片预加载

图片预加载的实现方法 在Vue中实现图片预加载可以提升用户体验,避免图片加载延迟导致的空白或闪烁。以下是几种常见的方法: 使用JavaScript的Image对象 创建一个Image对象并设置其sr…

vue表格实现加载更多

vue表格实现加载更多

实现 Vue 表格加载更多的几种方法 滚动加载(无限滚动) 通过监听滚动事件,当滚动到底部时加载更多数据。适用于长列表或表格。 <template> <div clas…

vue实现视频预加载

vue实现视频预加载

实现视频预加载的方法 在Vue中实现视频预加载可以通过多种方式完成,关键在于提前加载视频资源,确保播放时流畅无卡顿。 使用<video>标签的preload属性 <templat…

vue懒加载实现方式

vue懒加载实现方式

Vue懒加载的实现方式 使用Vue异步组件 Vue允许将组件定义为异步加载的工厂函数,通过import()动态导入组件实现懒加载。这种方式适用于路由组件或按需加载的组件。 const AsyncCo…