Skip to content

Instantly share code, notes, and snippets.

@hyrious
Created September 14, 2023 02:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hyrious/d1e5042d70dd5fab33d25e2ad360d164 to your computer and use it in GitHub Desktop.
Save hyrious/d1e5042d70dd5fab33d25e2ad360d164 to your computer and use it in GitHub Desktop.
a trick to embed javascript resource in html
<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>
@hyrious
Copy link
Author

hyrious commented Sep 14, 2023

Note

{type: 'module'} is only allowed in secure context (localhost / https).
However without this option, this code can run in file://.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment