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

Chrome中加载动画与计时器正常,Safari中无刷新的问题求助

Safari上传时加载动画与计时器不刷新的解决办法

当使用传统表单同步提交(method="post"直接跳转)时,Safari会在触发提交后立即冻结当前页面主线程,停止JS定时器执行和UI渲染,全力处理文件上传与页面导航——这就是加载动画和计时器停住的核心原因。Chrome对该场景做了宽松优化,允许短暂UI更新,但Safari遵循更严格的导航阻塞机制。

解决方案:改用异步上传(Fetch API)

通过异步提交避免页面立即跳转,让JS和动画持续运行,上传完成后再手动跳转至目标页面。

修改后的HTML

<form id="uploadForm" method="post" enctype="multipart/form-data">
  <br>
  <div class="file-upload">
    <label for="upload" class="file-upload">Upload</label>
    <input type="file" name="pdf-file" class="file-upload" id="upload">
  </div>

  <h1 class="text-timer" id="timer"></h1>

  <br><br>
  <button type="submit">Submit</button>
</form>
<div class="load" style="display:none;">加载中...</div>

修改后的JS

const uploadForm = document.getElementById('uploadForm');
const loadingIcon = document.querySelector('.load');
const timer = document.getElementById('timer');

uploadForm.addEventListener('submit', async (e) => {
  // 阻止默认表单跳转行为
  e.preventDefault();
  
  // 启动加载动画与计时器
  loadingIcon.style.display = 'flex';
  loadingIcon.classList.add('spin-animation');
  
  let time = 0;
  const interval = setInterval(() => {
    time += 0.01;
    timer.textContent = time.toFixed(2) + " seconds";
  }, 10);
  
  try {
    // 构造表单数据
    const formData = new FormData(uploadForm);
    // 异步发送上传请求
    const response = await fetch('/upload', {
      method: 'POST',
      body: formData
    });
    
    // 上传完成后清理计时器并跳转
    clearInterval(interval);
    if (response.ok) {
      window.location.href = '/upload';
    }
  } catch (error) {
    // 处理上传错误
    clearInterval(interval);
    loadingIcon.style.display = 'none';
    loadingIcon.classList.remove('spin-animation');
    alert('上传失败:' + error.message);
  }
});

关键说明

  • 异步提交时当前页面主线程不会被阻塞,计时器和CSS动画可正常运行
  • 上传完成后通过window.location.href手动跳转,与原逻辑最终效果一致
  • 提前给.load元素设置display:none,避免页面初始加载时显示加载状态

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 10:52:18