Skip to content

location.href 的异步机制

window.location.href 的赋值,并不会中断 Javascript 的执行立即进行页面跳转。

js
(function(){
    window.location.href= 'http://www.baidu.com';
    console.log(123);
}())

上述代码不会立即执行页面跳转,而是会先输出 123,然后才会跳转到 baidu 页面。

如果不想输出 123,那么改成这样:

js
(function(){
    window.location.href= 'http://www.baidu.com';
    return 
    console.log(123);
}())

下面这些情况也都会执行。

html
<body>
  <button onClick="goto()">跳转</button>
  <script>
    console.log('重新加载页面')
    function goto() {
      window.location.href = 'https://www.baidu.com'
      // 情况一:会执行
      // Promise.resolve().then(() => {
      //   // 会执行
      //   alert('我执行了!')
      // })
      // 情况二:会执行
      // setTimeout(() => {
      //   alert('我执行了!')
      // }, 100)
      // 情况三:会执行,并且存储在原网页的域名下
        // setTimeout(() => {
        //   localStorage.setItem('windowPromise', '123456789')
        // }, 100)
    }
  </script>
</body>

Released under the MIT License.