MutationObserver、Worker 、MessageChannel也只是API的使用而已

weixin_34357887發表於2019-02-13

1.MutationObserver是觀察dom修改的新增API

<div id="app">
    <p class="aaa">我</p>
</div>
<script>
    //直接new傳一個回撥函式, observer.observe下面這行程式碼執行完,在dom被修改的時候,這個回撥函式就會被呼叫
    let observer = new MutationObserver(function (mutationsList) {
        for (var mutation of mutationsList) {
            let type = mutation.type;
            switch (type) {
                case "childList":
                    console.log("A child node has been added or removed.");
                    break;
                case "attributes":
                    console.log(`The ${mutation.attributeName} attribute was modified.`);
                    break;
                case "subtree":
                    console.log(`The subtree was modified.`);
                    break;
                default:
                    break;
            }
        }
    });
    //呼叫observe方法,傳入要觀察的dom物件,後面是配置,要觀察屬性的變化,孩子的增刪,子節點的修改
    observer.observe(document.getElementById('app'), { attributes: true, childList: true, subtree: true });
</script>
複製程式碼

2.Worker是彌補js做耗時任務的新API

//index.js
 let worker = new Worker('./calc.js');
 worker.postMessage(10000);
 worker.onmessage = function (e) {
   console.log(e.data);
 }
複製程式碼
//calc.js
// 注意這裡面不能操作dom
onmessage = function (e) {
  //可能算了很久!
  let res = caculate(e.data)
  postMessage(res);
}
複製程式碼

3.MessageChannel這個我也不知道有啥用,一般在頁面與ifram之間通訊

   let channel = new MessageChannel();
   let port1 = channel.port1;
   let port2 = channel.port2;
   port1.postMessage('hello');
   port2.onmessage = function (e) {
     console.log(e.data);
   };
複製程式碼
  • ps:以上都都是不阻塞程式碼執行的

相關文章