Creating a Web Worker in Codepen
Last updated: Mar 10, 2020
In trying to find a way to integrate javascript projects into this blog without loading special seperate css and js files into my markdown, I came across some built-in hugo shortcode for codepen. After some tinkering I was able to embed codepen projects right into my markdown using just the slug
(as in: {{<codePen xxxxxxx>}}).
However I then ran into the issue of trying to load any generic worker.js file to get a web worker running. There is no way of identifying the code in the javascript pen as one file or another such that it could be called using:
worker = new Worker("worker.js");
And so it seems as though codepen requires inline js workers. I found some resources here and an example here that helped. Instead of loading a *.js file in externally, I can create an inline worker using Blob(). Blob() essentially loads the worker code as a string, which can then be used to create a unique URL, which can then be used to load a new Worker object:
var blob = new Blob([document.getElementById("worker").textContent],
{
type: "application/javascript"
});
var blobURL = window.URL.createObjectURL(blob);
var worker = new Worker(blobURL);
In my case, I used the element id to load the script content. This way I can put the worker script with the html and load it from the javascript pen the same way an external *.js might be loaded.