英文:
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>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论