2017-04-24 337 views
0

我想在web worker中使用defiant.js,因为除了JSON.search之外,我还在做繁重的计算。 不过,我不断收到一个使用importScripts的web worker错误(defiant.min.js)

Uncaught Error: Uncaught ReferenceError: Defiant is not defined

我创建使用挑衅的演示代码的一部分,一个简单的例子。

有谁知道这是一个defiant.js问题还是我只是导入脚本错了? 或者还有其他的解决方案可以做到这一点?

JS在main.html中

var obj = { 
    "car": [ 
     {"id": 10, "color": "silver", "name": "Volvo"}, 
     {"id": 11, "color": "red", "name": "Saab"}, 
     {"id": 12, "color": "red", "name": "Peugeot"}, 
     {"id": 13, "color": "yellow", "name": "Porsche"} 
    ], 
    "bike": [ 
     {"id": 20, "color": "black", "name": "Cannondale"}, 
     {"id": 21, "color": "red", "name": "Shimano"} 
    ] 
} 
    var worker = new Worker('defiantWW.js'); 


    worker.addEventListener('message', function(e) { 
     console.log(e.data); 
    }, false); 
    worker.postMessage(obj); 

网络工作者文件

self.addEventListener('message', function(e) { 
    importScripts('defiant.min.js') 
    var obj=e.data; 
    var search = JSON.search(obj, '//car[color="yellow"]/name'); 
    self.postMessage(search); 
}, false); 

编辑 改变importScripts的)位置(由dandavis的意见建议 - 但同样的结果

网worker file v2

importScripts('defiant.min.js') 
self.addEventListener('message', function(e) { 
    var obj=e.data; 
    var search = JSON.search(obj, '//car[color="yellow"]/name'); 
    self.postMessage(search); 
}, false); 
+1

你应该上前线的负载,而不是在每封邮件进口,这可能搞砸 – dandavis

+0

谢谢 - 改变了importScripts的位置()并编辑了问题,但结果保持不变。 – Kristian

回答

0

令人遗憾的是,defiantJS不支持在网络工作者中使用。 在这个问题上得到了feedback from Hakan Bilgin

There is already support for web workers in Defiant.js

<script src="defiant.min.js"></script> 
<script> 

var obj = { 
    "car": [ 
     {"id": 10, "color": "silver", "name": "Volvo"}, 
     {"id": 11, "color": "red", "name": "Saab"}, 
     {"id": 12, "color": "red", "name": "Peugeot"}, 
     {"id": 13, "color": "yellow", "name": "Porsche"} 
    ], 
    "bike": [ 
     {"id": 20, "color": "black", "name": "Cannondale"}, 
     {"id": 21, "color": "red", "name": "Shimano"} 
    ] 
}; 

Defiant.getSnapshot(obj, function(snapshot) { 
    var found = JSON.search(snapshot, '//car'); 
    console.log(found); 
}); 

</script> 

[Snapshot] doesn't give me access to defiant from within my own web-worker. I can execute the Snapshot in the main thread and then post the result to my web-worker, however the large JSON (5-15mb) is handled only in the web-worker. I would have to pass it over to the main thread, run the Snapshot (which is executed in another web-worker) and then pass the result back to my WW. Since I'm using the JSON.search quite often that would induce a lot of unnecessary overhead on the main thread.

No...you can not access Defiant from within a web worker

相关问题