importScripts();/* imports nothing */
importScripts('foo.js'); /* imports just "foo.js" */
importScripts('foo.js', 'bar.js');/* imports two scripts */
导入以后,可以直接使用这些文件中的方法。看一个网上的小例子:
复制代码
代码如下:
/**
* 使用 importScripts 方法引入外部资源脚本,在这里我们使用了数学公式计算工具库 math_utilities.js
* 当 JavaScript 引擎对这个资源文件加载完毕后,继续执行下面的代码。同时,下面的的代码可以访问和调用
* 在资源文件中定义的变量和方法。
**/
importScripts('math_utilities.js');
onmessage = function (event)
{
var first = event.data.first;
var second = event.data.second;
calculate(first,second);
};
function calculate(first,second) {
//do the calculation work
var common_divisor=divisor(first,second);
var common_multiple=multiple(first,second);
postMessage("Work done! " +
"The least common multiple is " + common_divisor +
" and the greatest common divisor is "+common_multiple);
}
Shared worker example: how to use shared worker in HTML5
send instructions to shared worker:
脚本文件代码:
复制代码
代码如下:
// 创建一个共享线程用于接收从不同连接发送过来的指令,指令处理完成后将结果返回到各个不同的连接用户。
var connect_number = 0;
onconnect = function(e) {
connect_number =connect_number+ 1;
//get the first port here
var port = e.ports[0];
port.postMessage('A new connection! The current connection number is '
+ connect_number);
port.onmessage = function(e) {
//get instructions from requester
var instruction=e.data.instruction;
var results=execute_instruction(instruction);
port.postMessage('Request: '+instruction+' Response '+results
+' from shared worker...');
};
};
/*
* this function will be used to execute the instructions send from requester
* @param instruction
* @return
*/
function execute_instruction(instruction)
{
var result_value;
//implement your logic here
//execute the instruction...
return result_value;
}
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn