gpt4 book ai didi

javascript - 如何检查页面重新加载是否完成

转载 作者:行者123 更新时间:2023-12-01 16:04:28 25 4
gpt4 key购买 nike

我有一个用户单击的按钮,它提交表单并在提交时重新加载页面。我想检查页面的重新加载是否完成。我尝试使用下面的
但这会在表单提交后甚至在加载完成之前直接发出警报。

if(window.performance.navigation.type == 0){
alert('loaded');
}

如何检查加载是否完成。提前致谢!

最佳答案

DOMContentLoaded 和 Load 可用于此目的 (link)

DOMContentLoaded – the browser fully loaded HTML, and the DOM tree is built, but external resources like pictures and stylesheets may be not yet loaded.

load – not only HTML is loaded, but also all the external resources: images, styles etc.



Load 应该只用于检测完全加载的页面。在 DOMContentLoaded 更合适的地方使用 load 是一个常见的错误。
    window.addEventListener('DOMContentLoaded', (event) => {
console.log('DOM fully loaded and parsed');
});

//===================

window.onload = function() {
// same as window.addEventListener('load', (event) => {
alert('Page loaded');

// image is loaded at this time
alert(`Image size: ${img.offsetWidth}x${img.offsetHeight}`);
};

根据您的问题,您希望在提交表单后进行检查。因此,当表单提交时,窗口会重新加载,整个文档也会重新加载。

您也可以使用 document.readyState 检查文件是否装满。

The document.readyState property can be used to check if the document is ready. From MDN:

Values The readyState of a document can be one of following:

loading – The document is still loading. interactive – The document has finished loading and the document has been parsed but sub-resources such as images, stylesheets and frames are still loading. complete – The document and all sub-resources have finished loading. The state indicates that the load event is about to fire.



您可以使用以下代码。
    if(document.readyState === "complete") {
// Fully loaded!
}
else if(document.readyState === "interactive") {
// DOM ready! Images, frames, and other subresources are still
downloading.
}
else {
// Loading still in progress.
// To wait for it to complete, add "DOMContentLoaded" or "load"
listeners.

window.addEventListener("DOMContentLoaded", () => {
// DOM ready! Images, frames, and other subresources are still
downloading.
});

window.addEventListener("load", () => {
// Fully loaded!
});
}

关于javascript - 如何检查页面重新加载是否完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60767556/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com