WebWorker的importScripts方法

简述

  在《JavaScript高级程序设计(第三版)》中,提到WebWorker的importScripts方法是异步执行的,然而在

另一本书《Javascript权威指南》中,却说importScripts是一个同步方法,两者矛盾,故私底下测试一番,发现

该方法确实是同步执行,待所有js问价解析执行完毕再执行后续代码。

  另外,importScripts方法是可以嵌套执行的。

  如:

  index.html:

    <script>
        var w = new Worker("worker1.js");
        w.onmessage = function(e){
            console.log(e.data)
        }
        w.postMessage("from index ...")
    </script>

  work1.js:

  importScripts("t1.js");
  console.log("worker1.js");
  onmessage = function(e){
      console.log(e.data)
  }

  t1.js:

    importScripts("t2.js")
    console.log("this is the t1.js ...")
    

  t2.js:

    console.log("this is the t2.js ...")

 

  返回结果:

  

    this is the t2.js ... 
    this is the t1.js ...
    worker1.js
    from index ...  

其他

  worker线程,同步运行代码,当worker线程并没有绑定onmessage事件处理程序并且没有其他异步回调或者定时器外,代码执行完毕就销毁该线程。如果线程没有onmessage,但是有异步回调,则等待回调执行。

posted @ 2015-01-07 10:24  royalrover  阅读(13127)  评论(0编辑  收藏  举报