Skip to content

Instantly share code, notes, and snippets.

@sherbondy
Last active January 23, 2017 20:04
Show Gist options
  • Save sherbondy/66dd2ba7500cf6b5d41203290228e699 to your computer and use it in GitHub Desktop.
Save sherbondy/66dd2ba7500cf6b5d41203290228e699 to your computer and use it in GitHub Desktop.
Example of running google-closure-js in the browser via a Web Worker
<html>
<head>
<title>Closure Compiler JS Browser Demo</title>
</head>
<body>
<div>
<textarea id="src" name="" cols="80" rows="10">
// example script
var x = 1;
function square(x) {
var y = (x*x);
return y;
}
var z = square(2);
console.log(z);
</textarea>
<button id="compile" onclick="compile_me()">
compile
</button>
</div>
<div id="result" style="border: solid gray;">
// the compilation will appear here
</div>
<script type="text/javascript">
var compiler_worker = new Worker("worker.js");
function compile_me(){
var result = document.getElementById('result');
result.innerText = "//compiling...";
var input_src = document.getElementById("src").value;
var flags = {
jsCode: [{src: input_src}],
env: "CUSTOM",
compilationLevel: "SIMPLE"
};
compiler_worker.postMessage(flags);
}
compiler_worker.onmessage = function(e) {
console.log("compilation result received from worker.");
result.innerText = e.data;
}
</script>
</body>
</html>
importScripts('jscomp.js');
onmessage = function(e) {
console.log("Message received from main script.");
var flags = e.data;
var compiled_result = compile(flags);
console.log("Compilation completed, sending result to main process.");
postMessage(compiled_result.compiledCode);
}
@sherbondy
Copy link
Author

Also, if you are having trouble getting google-closure-compiler-js setup/installed from source, here's a quick example of a shell session for setting things up so you actually wind up with a working jscomp.js file:
https://gist.github.com/sherbondy/c589a215c3cdc6e12c9666d0706af581

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