beforeunload事件和Content-Disposition=attachment。

5

最近我在我的代码中添加了如下内容:

$(window).on('beforeunload', function () {
    $('.whirly-loader').show(); //SPINER
})

当用户进入我的网站的另一侧时,旋转器就会显示出来。大部分情况下都能正常运行。 但是,在应用程序的某些部分中,客户端开始访问另一侧,服务器响应如下标头:

Cache-Control
    max-age=0, must-revalidate, private
Connection
    Keep-Alive
Content-Disposition
    attachment;filename=suministro.csv
Content-Type
    text/csv; charset=utf-8
[...]

这可以防止页面重新加载,只显示用于下载或打开文档的窗口。 我的问题是,即使页面停止加载,旋转图标仍然会出现。

即使由于标头而不重新加载页面,也应该隐藏旋转图标的事件是什么?


我认为没有任何事件可以监听这个。最多你可以尝试设置一个超时时间,在一段时间后如果没有加载新页面,再次禁用你的旋转器。或者,如果你知道哪些方式“离开”页面会触发特定的响应,你可以尝试某种方式来确定它(在相应的链接/提交按钮上单击处理程序),并且在这些情况下一开始就不显示旋转器。 - CBroe
浏览器已经显示进度指示器了。不要自己制作。这是糟糕的用户体验实践,不应该这样做。 - Brad
相关:https://dev59.com/6m855IYBdhLWcg3wsWhq#13698030 - djvg
3个回答

0

您可以为下载链接添加target属性。

例如:

<body onbeforeunload="document.body.style.backgroundColor = 'red';">
    <a href="output.zip" target="_blank">Download</a>
</body>

属性target="_blank"会导致onbeforeload事件不触发。


问题在于并不总是有一个按钮。另一方面,这是一个非常大的网站,我正在寻找一个通用解决方案。 - Efeyabel

0
我们曾经遇到过类似的问题,并找到了手动解决方法(在您的情况下,手动显示一个旋转器),例如:

$('.js-show-spinner').addEventListener('click', event => {
  event.preventDefault();
  $('.whirly-loader').show(); //SPINER
});
<a href="https://google.com">google.com</a>
<a class="js-show-spinner" href="/home">Home</a>
<a href="SOME_DOC" download>some doc</a>


0
这个 jQuery 插件使用 window 对象将其 beforeunload 事件绑定到 body 元素上,因此实现起来非常简单,并且提供了一个通用的解决方案。

;(function($, window, document){

  $.fn.plgn = function() {

    //Start the loader when the event beforeunload
    $(window).on('beforeunload', function(event){
      event.stopPropagation();
      console.log("whirly-loader show");

      //Hide the loader after 5 seconds if the page fails to load
      setTimeout(function(){
        console.log("whirly-loader hide");  
      }, 5000);
    });

  }

})(jQuery, window, document);

//Start the loader as soon as javascript loads
console.log("whirly-loader show");

$( document ).ready(function() {
  //Hide the loader when the page is completely loaded
  console.log("whirly-loader hide");
  $("body").plgn();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="button" value = "Refresh page" onclick="window.location.reload();" />


目前你的回答不够清晰,请编辑并添加更多细节,以帮助其他人理解它如何回答问题。你可以在帮助中心找到有关如何撰写好答案的更多信息。 - Community

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接