復制代碼代碼如下: 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; }