Created
September 14, 2023 02:24
-
-
Save hyrious/d1e5042d70dd5fab33d25e2ad360d164 to your computer and use it in GitHub Desktop.
a trick to embed javascript resource in html
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script id="worker" src="data:,"> | |
// the empty "src" prevents code inside this block from being executed! | |
// this is the source code of the worker. | |
postMessage("Hello world!") | |
</script> | |
<script> | |
var blob = new Blob([document.getElementById('worker').textContent], | |
{type: 'application/javascript'}) | |
var worker = new Worker(URL.createObjectURL(blob), {type: 'module'}) | |
worker.onmessage = (ev) => { | |
console.log(ev.data) | |
} | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note
{type: 'module'}
is only allowed in secure context (localhost / https).However without this option, this code can run in
file://
.