简体   繁体   English

为什么更改 `window.location.href` 不能作为回报?

[英]Why changing `window.location.href` doesn't work as a return?

I would have expected, that in the following function the first window.location.href works as a return, gets redirected to example.com , and the rest of the code would be ignored. I would have expected, that in the following function the first window.location.href works as a return, gets redirected to example.com , and the rest of the code would be ignored.

() => {
  window.location.href = 'http://example.com/'; // Does nothing
  console.log('does it log?'); // Yes, it logs
  window.location.href = 'http://example.org'; // Redirects here
}

Navigating to another page sounds like a definitive stop: discard DOM, abandon XHR queries, leave the site etc. Why the rest is still executed?导航到另一个页面听起来像是一个彻底的停止:丢弃 DOM、放弃 XHR 查询、离开站点等。为什么 rest 仍然执行?

Short answer - it depends on the browser's speed of doing the redirect to the other page, hence unpredictable.简短的回答 - 这取决于浏览器重定向到其他页面的速度,因此无法预测。

What's happening here is that the browser will try to execute the code after这里发生的是浏览器将尝试执行代码之后

window.location.href = 'http://example.com/';

Until the redirect occures and the page will go to the next web adress the rest of the code will execute as it supposed to run regular so the number of lines of code that will be executed actually depends on the browser's speed of doing the actual redirecting.直到发生重定向并且页面将 go 到下一个 web 地址 rest 的代码将执行,因为它应该正常运行,因此实际执行的重定向代码的行数取决于浏览器的实际执行速度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM