D
D
Dmitry Kachurinets2016-06-18 14:26:34
JavaScript
Dmitry Kachurinets, 2016-06-18 14:26:34

I am studying how the Web Workers API works and the first simple script using it does not work. What am I doing wrong?

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Ping Pong</title>
    <script src="manager.js"></script>
</head>
<body>
    <p id="output"></p>
</body>
</html>

//manager.js
 
window.onload = function() {
    var worker = new Worker("worker.js");
 
    worker.postMessage("ping");
 
    worker.onmessage = function (event) {
        var message = "Worker says " + event.data;
        document.getElementById("output").innerHTML = message;
    };
}
 
//worker.js
 
onemessage = pingPong;
 
function pingPong(event) {
    if (event.data == "ping") {
        postMessage("pong");
    }
}

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
Dmitry Kachurinets, 2016-06-19
@angryblacker

The error was in the worker.js file. Instead of "onemessage" write "onmessage".

#
#algooptimize #bottize, 2016-06-18
@user004

var worker = new Worker('task.js');
from the Internet

A
Anton, 2016-06-19
@SPAHI4

If you are testing not on localhost, then the page must be opened via https

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question