简体   繁体   English

HTML 5 Worker“threads”,在Function上生成

[英]HTML 5 Worker “threads” , spawn on Function

I have been reading up on HTML 5 worker threads but all the samples i have seen seem to require the javascript be in its own file. 我一直在阅读HTML 5工作线程,但我看到的所有示例似乎都要求javascript在自己的文件中。

so im basicly wondering if its posible to start a worker work directly towards a function. 所以我基本上想知道它是否可以让一个工人直接开始工作。

The end goal here being something along the lines of: 这里的最终目标是:

function AllJavascriptIsLoaded()
{

if(gWorkersSupported)
{

        var Worker = new Worker(MyFunc)

        Worker.Start();
    }
    else 
    {
        // Horrible user experience incomming.
        MyFunc();
    }
}

function MyFunc()
{
    // Complex and time consuming tasks
}

vkThread plugin helps you to implement exactly what you requested. vkThread插件可帮助您准确实现所请求的内容。

take a look at http://www.eslinstructor.net/vkthread/ 看看http://www.eslinstructor.net/vkthread/

there are examples for different kind of functions: regular function, function with context, with dependencies, anonymous, lambda. 有不同类型的函数的例子:常规函数,带上下文的函数,带依赖性,匿名,lambda。

To my knowledge, this is not allowed for security reasons. 据我所知,出于安全原因,这是不允许的。 I'd assume that a child object, or any JS script in the same file, would potentially have access to the parent DOM window, which Web Workers are not allowed to access. 我假设子对象或同一文件中的任何JS脚本可能有权访问父DOM窗口,不允许Web Workers访问。

So, we're stuck with posting messages to other files unless someone finds a nicer way to do it ;) 所以,我们一直坚持将消息发布到其他文件,除非有人找到更好的方法去做;)

You can use something called inline-worker . 您可以使用称为inline-worker东西。

Basically you create a script resource via dataURI or BlobURL for the worker script. 基本上,您通过dataURI或BlobURL为worker脚本创建脚本资源。 Given that the content of the script can be generated, you can use Function.toString() to build the content of the worker. 鉴于可以生成脚本的内容,您可以使用Function.toString()来构建worker的内容。

Example use BlobURL: http://www.html5rocks.com/en/tutorials/workers/basics/ 示例使用BlobURL: http ://www.html5rocks.com/en/tutorials/workers/basics/
Example use both technique: https://github.com/jussi-kalliokoski/sink.js/blob/master/src/core/inline-worker.js 示例使用两种技术: https//github.com/jussi-kalliokoski/sink.js/blob/master/src/core/inline-worker.js

Jeffrey is right about the security restriction of WebWorker. Jeffrey对WebWorker的安全限制是正确的。 The code running in the worker cannot access the DOM, so it should only be used for calculation heavy tasks. 在worker中运行的代码无法访问DOM,因此它只应用于计算繁重的任务。 If you try to access the DOM inside worker's code it would raise an error. 如果您尝试在工作人员代码中访问DOM,则会引发错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM