Detecting Page Load or Reload Cancel Event 检测页面加载或重新加载取消事件

huangapple go评论90阅读模式
英文:

Detecting Page Load or Reload Cancel Event

问题

在页面加载/重新加载期间,如果点击取消按钮,则页面内容会部分加载。有没有更好的方式来处理这种情况?可以显示类似于“页面加载中断”的消息。

英文:

During page load/reload if the Cancel button is hit the page content is partially loaded. Instead of displaying partial content is there a better way to handle this?

Say showing a message like "Page load interrupted".

答案1

得分: 0

<!DOCTYPE html>
<html>
<head>
  <title>页面加载中断示例</title>
  <style>
    .message {
      display: none;
      font-size: 18px;
      color: red;
    }
  </style>
</head>
<body>
  <h1>页面加载中断示例</h1>

  <!-- 当页面加载中断时显示的消息元素 -->
  <div id="load-interrupted-message" class="message">
    页面加载中断。
  </div>

  <script>
    // 等待DOM完全加载
    document.addEventListener("DOMContentLoaded", function() {
      // 附加事件监听器到beforeunload事件
      window.addEventListener("beforeunload", function(event) {
        // 如果点击取消按钮,则显示消息
        document.getElementById("load-interrupted-message").style.display = "block";
        // 如有需要,自定义消息或执行其他附加操作
        event.returnValue = "页面加载中断。";
      });
    });
  </script>
</body>
</html>
英文:

Yes, you can handle the scenario of a canceled page load or reload by displaying a message to the user instead of partially loading the content. this is an example below, I added comments to show what does what.

<!DOCTYPE html>
<html>
<head>
  <title>Page Load Interrupted Example</title>
  <style>
    .message {
      display: none;
      font-size: 18px;
      color: red;
    }
  </style>
</head>
<body>
  <h1>Page Load Interrupted Example</h1>

  <!-- Message element to display when page load is interrupted -->
  <div id="load-interrupted-message" class="message">
    Page load interrupted.
  </div>

  <script>
    // Wait for the DOM to be fully loaded
    document.addEventListener("DOMContentLoaded", function() {
      // Attach an event listener to the beforeunload event
      window.addEventListener("beforeunload", function(event) {
        // Display the message if the Cancel button is hit
        document.getElementById("load-interrupted-message").style.display = "block";
        // Customize the message or take any additional actions if needed
        event.returnValue = "Page load interrupted.";
      });
    });
  </script>
</body>
</html>


huangapple
  • 本文由 发表于 2023年6月15日 14:34:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/76479727.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定