Can Web Workers Be Used Without Separate JavaScript Files?
The default approach for creating web workers involves writing them in separate JavaScript files and calling them as follows:
<code class="js">new Worker('longrunning.js')</code>
However, for those utilizing the Closure Compiler and preferring to avoid distributing workers in distinct files, there is an alternative solution:
Inline Workers with BLOB
HTTP5Rocks provides an innovative method for inline inline workers using the Blob() function. This technique allows you to generate your worker script dynamically or create self-contained pages without the need for external worker files.
<code class="js">var blob = new Blob([ document.querySelector('#worker1').textContent ], { type: "text/javascript" }); var worker = new Worker(window.URL.createObjectURL(blob));</code>
In this example, the textContent property of the HTML script element with id="worker1" is retrieved and used to construct a Blob object with the appropriate MIME type. A new worker is then created with a URL created using the Blob's createObjectURL() method. This URL is unique to the Blob and allows the worker to be loaded and executed without a separate JavaScript file.
The above is the detailed content of Can Web Workers Be Implemented Without Separate JavaScript Files?. For more information, please follow other related articles on the PHP Chinese website!