Search code examples
javascriptworker

Create worker from data URI


I have a very simple need, I need to spawn a webworker with a small data uri script:

new Worker('data:,console.log("HI")');

In Firefox this is giving me instead an error. Error is:

 SecurityError: Failed to load worker script at "data:,console.log("HI")"

Is there anyway to get worker to work with data URI?


Solution

  • You could definitely try Freelancer which:

    • Takes a function that it transforms to a string using Function.prototype.toString
    • Creates an IIFE from the passed function and passes in any additional arguments
    • Transforms the function into a Blob with application/javascript as the type
    • Instantiates the new worker with the data URI created with URL.createObjectURL.