Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Can I use Other Libraries in a Web Worker?

I have some javascript code like this,

var worker = new Worker("javascript/worker.js");

worker.onmessage = function(evt)
{
    // stuff
}

worker.js looks like this,

importScripts("base.js");

function getImage()
{
    $.ajax({
    url: 'URL'
    dataType: "text/plain; charset=x-user-defined",
    mimeType: "text/plain; charset=x-user-defined",
    success: function(data, textStatus, jqXHR)
    {
        callback();
    }
});
}

The worker.js file does not have jQuery included so that doesn't work. If I add this to worker.js,

importScripts("jQuery.js");

Then I get the message,

Uncaught ReferenceError: window is not defined

I'm not really familiar with workers. Am I right in thinking this it is loading the worker.js code in a completely separate environment (basically a background thread) so it doesn't have access to window.

like image 444
peter Avatar asked Feb 09 '12 02:02

peter


1 Answers

On the worker's .js file:

importScripts('../relative/path/lib.min.js', '../../other/lib.js');
like image 118
REAPP3R Avatar answered Oct 07 '22 22:10

REAPP3R