当前位置:首页 > JavaScript

js实现加载更多内容

2026-01-30 15:26:51JavaScript

实现滚动加载更多内容

使用Intersection Observer API监听元素是否进入视口,触发加载更多操作。这种方法性能较好,避免频繁计算滚动位置。

const observer = new IntersectionObserver((entries) => {
  entries.forEach(entry => {
    if (entry.isIntersecting) {
      loadMoreContent();
    }
  });
});

const sentinel = document.querySelector('#load-more-trigger');
observer.observe(sentinel);

function loadMoreContent() {
  // 获取新内容逻辑
  fetch('/api/load-more')
    .then(response => response.json())
    .then(data => {
      // 将新内容插入DOM
      const container = document.querySelector('#content-container');
      data.items.forEach(item => {
        container.appendChild(createItemElement(item));
      });
    });
}

按钮点击加载更多

实现一个简单的点击加载更多按钮的方案,适合基础需求。

document.querySelector('#load-more-btn').addEventListener('click', () => {
  const currentPage = parseInt(btn.dataset.page) || 1;
  fetch(`/api/items?page=${currentPage + 1}`)
    .then(response => response.json())
    .then(data => {
      if (data.items.length) {
        btn.dataset.page = currentPage + 1;
        renderItems(data.items);
      } else {
        btn.disabled = true;
        btn.textContent = '没有更多内容';
      }
    });
});

function renderItems(items) {
  const container = document.querySelector('#items-container');
  items.forEach(item => {
    container.appendChild(createItemElement(item));
  });
}

无限滚动实现

结合滚动事件和节流函数实现传统无限滚动方案。

let isLoading = false;
window.addEventListener('scroll', throttle(() => {
  const scrollPosition = window.scrollY + window.innerHeight;
  const documentHeight = document.documentElement.scrollHeight;

  if (scrollPosition >= documentHeight - 300 && !isLoading) {
    isLoading = true;
    document.querySelector('#loading-indicator').style.display = 'block';

    fetchMoreData()
      .then(data => {
        appendData(data);
        isLoading = false;
        document.querySelector('#loading-indicator').style.display = 'none';
      });
  }
}, 200));

function fetchMoreData() {
  return fetch('/api/more-data').then(res => res.json());
}

分页加载优化

实现带分页的加载更多功能,包含错误处理和加载状态。

let currentPage = 1;
const pageSize = 10;

async function loadMore() {
  try {
    showLoading();
    const response = await fetch(`/api/data?page=${currentPage}&size=${pageSize}`);
    const newData = await response.json();

    if (newData.length) {
      renderData(newData);
      currentPage++;
    } else {
      showNoMore();
    }
  } catch (error) {
    showError();
  } finally {
    hideLoading();
  }
}

function showLoading() {
  document.querySelector('#loader').classList.remove('hidden');
}

function hideLoading() {
  document.querySelector('#loader').classList.add('hidden');
}

虚拟滚动优化

对于大量数据,考虑实现虚拟滚动提高性能。

js实现加载更多内容

class VirtualScroll {
  constructor(container, items, itemHeight) {
    this.container = container;
    this.items = items;
    this.itemHeight = itemHeight;
    this.visibleItems = Math.ceil(container.clientHeight / itemHeight);
    this.startIndex = 0;

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

  handleScroll() {
    const scrollTop = this.container.scrollTop;
    this.startIndex = Math.floor(scrollTop / this.itemHeight);
    this.render();
  }

  render() {
    const endIndex = Math.min(
      this.startIndex + this.visibleItems,
      this.items.length
    );

    const fragment = document.createDocumentFragment();
    for (let i = this.startIndex; i < endIndex; i++) {
      const item = document.createElement('div');
      item.className = 'item';
      item.style.height = `${this.itemHeight}px`;
      item.textContent = this.items[i];
      fragment.appendChild(item);
    }

    this.container.innerHTML = '';
    this.container.appendChild(fragment);
    this.container.style.height = `${this.items.length * this.itemHeight}px`;
  }
}

注意事项

  • 使用防抖或节流优化滚动事件处理
  • 考虑添加加载状态指示器
  • 实现错误处理机制
  • 移动端需要特殊处理触摸事件
  • 大量数据时考虑虚拟滚动技术
  • API设计应考虑分页参数和返回格式

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

相关文章

vue实现延迟加载

vue实现延迟加载

Vue 实现延迟加载的方法 使用动态导入(Dynamic Import)和异步组件 在 Vue 中,可以通过动态导入语法结合异步组件实现延迟加载。这种方式会在需要时才加载组件,而不是在初始加载时一并加…

vue 实现加载更多

vue 实现加载更多

Vue 实现加载更多功能 实现加载更多功能通常结合分页数据与滚动事件监听,以下是几种常见方法: 滚动监听 + 分页加载 监听滚动事件,当滚动到底部时触发加载更多数据: <template&g…

vue 实现模块加载

vue 实现模块加载

Vue 实现模块加载的方法 使用动态导入(Dynamic Import) 动态导入是 ECMAScript 模块系统的特性,Vue 项目可以通过 import() 语法实现按需加载模块。这种方式在构建…

vue 实现点击更多

vue 实现点击更多

Vue 实现点击更多功能 在Vue中实现点击更多功能通常涉及展示部分内容,点击按钮后展开剩余内容。以下是几种常见实现方式: 使用v-show或v-if控制显示 通过布尔值变量控制内容的展开与收起:…

vue实现异步加载

vue实现异步加载

Vue 异步加载的实现方法 在 Vue 中实现异步加载可以通过多种方式完成,包括动态导入、路由懒加载和异步组件等。以下是几种常见的实现方法: 动态导入与异步组件 使用 Vue 的 defineAsy…

vue怎么实现加载速度

vue怎么实现加载速度

优化 Vue 项目的加载速度 代码分割与懒加载 使用动态导入(import())实现路由懒加载和组件懒加载。在路由配置中,将组件改为函数形式动态加载: const Home = () => i…