yuxino / blog

🎬 Life's a Movie
17 stars 2 forks source link

你不知道的location.href #69

Closed yuxino closed 3 years ago

yuxino commented 6 years ago

在工作中发现了一个现象。location.href跳转的时机是在主线程执行完后才执行的。

跳转的时机

这里用了一个递归的fib(斐波那契算法)来模拟耗时操作。

Html 部分

<input type="button" id="btn" value="嘎嘎嘎"> 

Js 部分

function fib(index){
    if (index<0) {
        return 0;
    }
    if (index<=2) {
        return 1;
    }
    return fib(index-1) + fib(index-2);
}

var btn = document.getElementById('btn');
var q = 0
btn.onclick = function(){
  location.href = "https://codepen.io/Nbsaw";
  var q = fib(40);
  console.log(q);
}

代码丢codepen

利用location.href打开App

拿知乎举个例子。可以直接在手机上尝试一下。

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>this's a demo</title>
  <meta name='apple-itunes-app' content='app-id=477927812'>
</head>
<body>
  <a href="javascript:;" id="openApp">知乎客户端</a>
</body>
</html>
<script type="text/javascript">
  document.getElementById('openApp').onclick = function(e){
    if(navigator.userAgent.match(/(iPhone|iPod|iPad);?/i)) {
      location.href = "zhihu://app";
      setTimeout(function() {
        location.href = "https://itunes.apple.com/cn/app/id477927812";
      }, 2000)
    }
    if(navigator.userAgent.match(/android/i)) {
      window.location.href = "zhihu://app";
      window.setTimeout(function() {
        location.href = "https://****.apk";//android 下载地址
      }, 2000)
    }
  };
</script>