You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在jQuery的load函数执行时添加Loading Gif?

实现Load加载时显示Loading Gif的方案

嘿,这个需求很常见,我来给你梳理下怎么做——不需要把Loading Gif嵌入到load函数里,反而通过分离UI元素和加载逻辑会更灵活易维护。

步骤1:在页面中添加Loading动画元素

先在HTML里准备好你的Loading Gif容器,默认可以设置为隐藏(或者根据需求初始显示):

<!-- Loading动画容器 -->
<div id="loadingIndicator" style="display: none; text-align: center; padding: 20px;">
  <img src="/path/to/your-loading.gif" alt="加载中..." />
</div>
<!-- 用来展示加载内容的目标容器 -->
<div id="myinfo"></div>

步骤2:修改jQuery Load逻辑,控制Loading状态

利用load方法的回调函数,我们可以在加载开始前显示动画,加载完成(包括成功或失败)后隐藏动画:

// 加载开始:显示Loading动画
$('#loadingIndicator').show();

// 执行内容加载,完成后触发回调
$('#myinfo').load('/data/myinfo.html', function(response, status, xhr) {
  // 无论加载成功还是失败,先隐藏Loading动画
  $('#loadingIndicator').hide();
  
  // 可选:处理加载失败的情况
  if (status === "error") {
    $('#myinfo').html(`加载失败:${xhr.status} ${xhr.statusText}`);
  }
});

为什么不嵌入Gif到Load里?

load函数的核心作用是加载外部HTML内容并插入到目标元素中,而Loading状态是页面交互的过渡效果,把它作为独立的UI元素控制,不仅逻辑清晰,还能方便调整样式、复用动画,甚至在多个加载场景中重复使用这个Loading容器。

内容的提问来源于stack exchange,提问作者Becca Alley

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:48:25