John
John

Reputation: 281

Using webworkers, jquery returns undefined

i'm trying to make a webworker that will fetch some stuff from a server every n ms as poc for something i need. But i have a problem, i'm trying to use $.ajax inside my webworker and even if i defined the jquery in the html file it will say that $ is not defined, and i don't know how exactly i can use jquery inside the my worker.js file. I think that the main issue is that when i create a worker i specify the file as "new Worker("worker.js");" and i think that this messes up with jquery and so the jquery isn't assotiated with my worker js. I may be mistaken. I don't know how exactly i can solve this.

This is my html file:

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="worker.js"></script>
</head>
<body>

<p>output: <output id="result"></output></p>
<button onclick="worker()">Start Worker</button>

<script>
var w;

function worker() {
        w = new Worker("worker.js");
        w.onmessage = function(event) {
            document.getElementById("result").innerHTML = event.data;
        };
}
</script>

</body>
</html>

I don't exactly need to have a reference to worker.js in my header, i just tried to check if i add it there would it make any difference, but it doesn't.

And here's my worker:

var i = 0;

function someAjax (){
    $.get("https://httpbin.org/get", function(data, status){
        return data;
    });
}
function doSomething() {
    var test = someAjax();
    postMessage(test);
    setTimeout("doSomething()",500);
}

doSomething();

That website in the worker is some random site i found online to test webservices, on my side i'm querying my localhost.

the message i get is ReferenceError: $ is not defined So i'm searching a way to get the $ in my worker.js

Upvotes: 0

Views: 529

Answers (1)

guest271314
guest271314

Reputation: 1

The default jQuery script cannot be used within a WorkerGlobalScope thread as WorkerGlobalScope does not have a document, which will cause a TypeError when .createElement() is called within jQuery. You can alternatively use fetch() within the Worker thread. As noted by @epascarello call postMessage() within .then() handler to post the data to the main thread

var i = 0;

function someAjax () {
    // note `return` statement
    return fetch("https://httpbin.org/get")
           .then(response => response.text())
           .catch(err => { throw err })
}
function doSomething() {
    var test = someAjax();
    someAjax().then(test => {
      postMessage(test);
      setTimeout("doSomething()",500);
    })
    // handle error here
    .catch(err => console.error(err))  
}

doSomething();

Upvotes: 1

Related Questions