英文:
How to handle transient error during page reload in javascript?
问题
当您启动 window.location.reload()
时,如何处理瞬时网络错误中断页面加载的风险?是否有一种方法可以使脚本持续监视重新加载的结果,以确认是否成功,如果不成功,然后等待30秒并重试?
英文:
When you kick off a window.location.reload()
, what can you do about the risk of a transient network error interrupting the page load? Is there some way that the script can persist and monitor the result of the reload to confirm that it succeeded, and if not then wait 30 seconds and try again?
答案1
得分: 1
你可以在浏览器更改页面时无法控制它,但可以检查navigator.onLine
是否为true,然后根据情况重新加载或等待。
async function attemptReload() {
console.log('trying to reload')
if (!navigator.onLine) {
console.log('nope')
setTimeout(attemptReload, 30 * 1000);
return;
}
console.log('yep')
location.reload();
}
document.querySelector('#reload').addEventListener('click', attemptReload);
另一种更健壮的方法是向服务器发送fetch()
请求。如果请求成功,那么一切正常。如果不成功,那么就像上面那样等待。
英文:
While you can't take control of the browser while it's changing pages, you can check if navigator.onLine
is true, then reload or wait depending on it.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
async function attemptReload() {
console.log('trying to reload')
if (!navigator.onLine) {
console.log('nope')
setTimeout(attemptReload, 30 * 1000);
return;
}
console.log('yep')
location.reload();
}
document.querySelector('#reload').addEventListener('click', attemptReload);
<!-- language: lang-html -->
<button id='reload'>reload</button>
<!-- end snippet -->
Another, perhaps more robust approach, would be to send a fetch()
to the server. If the requests goes through, then you're OK. If not, then wait just like above.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论