当前位置:首页 > 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));
      });
    });
}

按钮点击加载更多

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

js实现加载更多内容

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

无限滚动实现

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

js实现加载更多内容

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

虚拟滚动优化

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

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 加载动画的实现方法 在 Vue 中实现加载动画可以通过多种方式完成,以下是一些常见的方法: 使用 CSS 动画 通过 CSS 定义动画效果,结合 Vue 的动态类绑定或条件渲染控制动画的显…

vue滚动加载实现

vue滚动加载实现

vue滚动加载实现 滚动加载是一种常见的优化手段,通过监听滚动事件动态加载数据,减少初始渲染压力。以下是几种实现方式: 使用IntersectionObserver API Intersectio…

vue加载动画实现

vue加载动画实现

Vue 加载动画实现方法 使用 CSS 动画或过渡 在 Vue 组件中可以直接通过 CSS 实现加载动画效果。定义一个简单的旋转动画: .loading-spinner { width: 40p…

react如何重新加载

react如何重新加载

重新加载当前页面 在React中重新加载当前页面可以通过window.location.reload()方法实现。该方法会强制浏览器重新加载当前URL,类似于按下F5刷新页面。 const relo…

jquery加载页面

jquery加载页面

jQuery 加载页面内容的方法 使用 .load() 方法 通过 AJAX 请求加载远程数据并插入到指定元素中。适用于加载部分页面片段。 $("#targetElement").load(…

vue实现滑动加载

vue实现滑动加载

滑动加载的实现思路 滑动加载通常通过监听滚动事件,判断是否滚动到页面底部来触发数据加载。Vue中可以通过结合v-for、@scroll事件和计算属性实现。 基础实现方法 监听滚动事件 在包含滚动区…