如何在JavaScript中处理页面重新加载期间的瞬态错误?

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

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(&#39;trying to reload&#39;)
  if (!navigator.onLine) {
    console.log(&#39;nope&#39;)
    setTimeout(attemptReload, 30 * 1000);
    return;
  }
  console.log(&#39;yep&#39;)
  location.reload();
}

document.querySelector(&#39;#reload&#39;).addEventListener(&#39;click&#39;, attemptReload);

<!-- language: lang-html -->

&lt;button id=&#39;reload&#39;&gt;reload&lt;/button&gt;

<!-- 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.

huangapple
  • 本文由 发表于 2023年5月14日 00:17:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/76243747.html
匿名

发表评论

匿名网友

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

确定