How to use web workers in same file as source | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

How to use web workers in same file as source

HTML5 Web workers normally require a separate file to be referred to in the source. Is there any way to create a web worker without creating a separate file?

23rd Dec 2016, 10:28 PM
Victor Durojaiye
Victor Durojaiye - avatar
2 Answers
+ 2
It can be done but the solution is pretty hacky and ugly. Only on Sololearn where the content must to be mixed together would I do this. I would never do this where I have freedom to use a separate file. Here is an example copied from https://stackoverflow.com/questions/5408406/web-workers-without-a-separate-javascript-file : // Build a worker from an anonymous function body var blobURL = URL.createObjectURL( new Blob([ '(', function(){ //Long-running work here }.toString(), ')()' ], { type: 'application/javascript' } ) ), worker = new Worker( blobURL ); // Won't be needing this anymore URL.revokeObjectURL( blobURL ); Tom must have misunderstood the question. The question wasn't "How do you put JavaScript in the same file as HTML?" It was "How do you put web workers in the same file?". Web workers are a much more advanced topic than how to use a script tag.
21st Jan 2020, 12:18 PM
Josh Greig
Josh Greig - avatar
+ 2
Yes. javascript can be included in the main HTML file using the <script> tag.
3rd Jun 2019, 4:33 PM
Tom
Tom - avatar