Is there a way to define a web worker inside the body of main html file? Something like this?
<!DOCTYPE html>
<html>
<body>
<script>
var worker = new Worker();// NO URL IS PROVIDED
worker.onmessage = function(event) {
alert("Reply: " + event.data);
}
worker.postMessage("Hello from index.html!");
</script>
</body>
</html>
In short: *Yes* it should be.
Web Workersrun in an isolated thread. As a result, the code that they execute needs to be contained in a separate file. But before we do that, the first thing to do is create a new Worker object in your main page. The constructor takes the name of the worker script:If the specified file exists, the browser will spawn a new worker thread, which is downloaded asynchronously. The worker will not begin until the file has completely downloaded and executed. If the path to your worker returns an 404, the worker will fail silently.
After creating the worker, start it by calling the
postMessage()method: