复制代码代码如下: 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); }
复制代码代码如下: !DOCTYPE html html head meta charset="UTF-8" title Shared worker example: how to use shared worker in HTML5 /title script var worker = new SharedWorker('sharedworker.js'); var log = document.getElementById('response_from_worker'); worker.port.addEventListener('message', function(e) { //log the response data in web page log.textContent =e.data; }, false); worker.port.start(); worker.port.postMessage('ping from user web page..'); //following method will send user input to sharedworker function postMessageToSharedWorker(input) { //define a json object to construct the request var instructions={instruction:input.value}; worker.port.postMessage(instructions); } /script /head body onload='' output id='response_from_worker' Shared worker example: how to use shared worker in HTML5 /output send instructions to shared worker: input type="text" autofocus oninput="postMessageToSharedWorker(this);return false;" /input /body /html
脚本文件代码:
复制代码代码如下: // 创建一个共享线程用于接收从不同连接发送过来的指令,指令处理完成后将结果返回到各个不同的连接用户。 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; }