Good all the time of day! Literally today, when using Web Workers, I encountered a problem in the importScripts () function, which is that Opera (I use version 11.61) for some internal reasons, when re-creating the object, the Worker refuses to execute the importScripts () function inside it ( only in opera, other browsers behave adequately).
A small example:
var str = "http://" + document.domain + "/classes/js/workers/worker.js"; var worker = new Worker(str); worker.onerror = function(e) { alert([ 'ERROR: Line ', e.lineno, ' in ', e.filename, ': ', e.message].join('')); } worker.onmessage = function (obj) { alert(obj['data']); } worker.postMessage();
')
Worker's code (suppose we have a global test variable in some.js):
onmessage = function () { importScripts("/classes/js/some.js"); postMessage(test); }
The above code, when first called, will faithfully output the contents of the test variable to us, but a repeated call instead of the expected value will display an error stating that the test variable is not defined. For what reasons the importScripts is not executed repeatedly, it is unknown. After trying for several hours, I found a solution. Everything is simple, since the opera does not want to re-import the scripts in the newly created object, we will not create the new object, we will create only one and make it global and in the future we will send everything through it. The previous code can be upgraded as follows:
if(!('worker' in window)) { var str = "http://" + document.domain + "/classes/js/workers/worker.js"; worker = new Worker(str); worker.onerror = function(e) { alert([ 'ERROR: Line ', e.lineno, ' in ', e.filename, ': ', e.message].join('')); } } worker.onmessage = function (obj) { alert(obj['data']); } worker.postMessage();
at the same time, the onmessage handler should not be placed inside the condition, since if the variables coming into the function are used inside it, a closure to the variables of the first call will be created, and the subsequent ones will be ignored.
I hope that the importScripts bug will be fixed soon, the technology is still fresh and sometimes you feel like a beta tester, and not a user ...
PS I hope the note will be useful to someone.