当前位置:首页 > 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实现懒加载,性能优于滚动事件监听。

js实现加载更多内容

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);
    });
}

按钮点击加载更多

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

js实现加载更多内容

<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() {
    // 获取新数据并更新列表
  }
}

性能优化建议

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

  • 使用防抖函数限制滚动事件触发频率
  • 添加加载状态指示器避免重复请求
  • 实现数据缓存减少服务器请求
  • 对于大量数据考虑虚拟滚动技术
  • 添加错误处理机制应对网络问题
// 防抖函数示例
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懒加载的实现难度 Vue懒加载的实现并不复杂,尤其是借助现代工具和库的支持。懒加载的核心思想是按需加载资源,通常用于路由或组件,以提升页面初始加载速度。以下是常见的实现方法和注意事项: 路由懒…

vue2实现图片懒加载

vue2实现图片懒加载

实现图片懒加载的方法 在Vue2中实现图片懒加载可以通过以下方法完成,核心原理是监听图片是否进入可视区域,再动态加载图片资源。 使用IntersectionObserver API Intersec…

vue 实现异步加载

vue 实现异步加载

Vue 异步加载的实现方法 动态导入组件(懒加载) 使用 import() 语法动态导入组件,Vue 会将其转换为异步加载的组件。适用于路由或组件按需加载。 const AsyncComponent…

vue实现预加载

vue实现预加载

vue实现预加载的方法 在Vue中实现预加载可以通过多种方式优化用户体验,以下是几种常见方法: 使用Webpack的魔法注释 通过import()语法结合Webpack的/* webpackPref…

vue实现触底加载

vue实现触底加载

触底加载的实现方法 在Vue中实现触底加载功能,可以通过监听滚动事件或使用Intersection Observer API来实现。以下是两种常见的方法: 监听滚动事件 在组件中监听滚动事件,计算…

vue 实现滚动加载

vue 实现滚动加载

Vue 实现滚动加载的方法 滚动加载(Infinite Scroll)是常见的前端功能,通过监听滚动事件动态加载数据。以下是Vue中实现滚动加载的几种方案: 使用原生滚动事件监听 通过监听窗口或容器…