Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enable Web Worker support #52

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

mallardduck
Copy link

@mallardduck mallardduck commented Mar 18, 2019

This commit allows the library to be imported within the context of a web worker. In a web worker, when a script is imported it is outside of the browser's scope and does not have access to window. Data must be passed back and forth between the main and worker thread(s).

Within the Worker, the self should be a sub-type of the WorkerGlobalScope object. The specific sub-type depends on the type of worker - but all workers scope are based on the former. Registering the library to self.cssbeautify allows worker's code to access it via this.cssbeautify.

This commit allows for this library to be imported within the context of a web worker. When a script is imported via a Worker the `self` should be a sub-type of the `WorkerGlobalScope` object.

Registering the library to `self.cssbeautify` allows workers to access it via `this.cssbeautify`.
@mallardduck
Copy link
Author

Figured I should provide some examples as clarity to why this is helpful:

Here's a file I call beautify-worker.js:

self.importScripts('/js/cssbeautify.min.js'); // This is the cssbeautify script with my PR.

onmessage = function(e) {
  let inputData = e.data;
  if (null === inputData) {
    postMessage('Please provide an input body');
  } else {
    let output = this.cssbeautify(inputData, {
      indent: '    ',
      openbrace: 'end-of-line',
      autosemicolon: true
    });
    postMessage({ response: output });
  }
}

Then in my main script, or one inline, you can have:

const beautifyWorker = new Worker('/js/beautify-worker.js');
beautifyWorker.onmessage = function(event) {
  // Do some things with the data returned by the worker!
  // With these examples, the beautified CSS is accessible at: event.data.response
};

And then set up a textbox with an event listener that has:

beautifyWorker.postMessage({
  input: data,
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

1 participant