Permalink
Browse files

utilise Web Worker whenever available

fixes #675
  • Loading branch information...
1 parent dd2a30d commit 24a292543a305a7949c96d5441501f7f18920657 @alexlamsl alexlamsl committed Nov 19, 2016
Showing with 52 additions and 12 deletions.
  1. +1 −1 Gruntfile.js
  2. +2 −1 assets/.eslintrc.json
  3. +34 −10 assets/master.js
  4. +15 −0 assets/worker.js
View
@@ -50,7 +50,7 @@ module.exports = function(grunt) {
src: ['tests/*.js', 'test.js']
},
web: {
- src: 'assets/master.js'
+ src: ['assets/master.js', 'assets/worker.js']
},
other: {
src: ['backtest.js', 'benchmark.js']
@@ -1,6 +1,7 @@
{
"env": {
- "browser": true
+ "browser": true,
+ "worker": true
},
"rules": {
"strict": [
View
@@ -1,7 +1,31 @@
(function() {
'use strict';
- var minify = require('html-minifier').minify;
+ var minify = (function() {
+ var minify = require('html-minifier').minify;
+ return function(value, options, callback, errorback) {
+ var minified;
+ try {
+ minified = minify(value, options);
+ }
+ catch (err) {
+ return errorback(err);
+ }
+ callback(minified);
+ };
+ })();
+ var worker = new Worker('worker.js');
+ worker.onmessage = function() {
+ minify = function(value, options, callback, errorback) {
+ postMessage({
+ value: value,
+ options: options
+ });
+ worker.onmessage = function(event) {
+ (typeof event.data === 'string' ? callback : errorback)(event.data);
+ };
+ };
+ };
function byId(id) {
return document.getElementById(id);
@@ -53,12 +77,11 @@
}
byId('minify-btn').onclick = function() {
- try {
- var options = getOptions(),
- originalValue = byId('input').value,
- minifiedValue = minify(originalValue, options),
- diff = originalValue.length - minifiedValue.length,
- savings = originalValue.length ? (100 * diff / originalValue.length).toFixed(2) : 0;
+ byId('minify-btn').disabled = true;
+ var originalValue = byId('input').value;
+ minify(originalValue, getOptions(), function(minifiedValue) {
+ var diff = originalValue.length - minifiedValue.length;
+ var savings = originalValue.length ? (100 * diff / originalValue.length).toFixed(2) : 0;
byId('output').value = minifiedValue;
@@ -68,11 +91,12 @@
'. Minified size: <strong>' + commify(minifiedValue.length) + '</strong>' +
'. Savings: <strong>' + commify(diff) + ' (' + savings + '%)</strong>.' +
'</span>';
- }
- catch (err) {
+ byId('minify-btn').disabled = false;
+ }, function(err) {
byId('output').value = '';
byId('stats').innerHTML = '<span class="failure">' + escapeHTML(err) + '</span>';
- }
+ byId('minify-btn').disabled = false;
+ });
};
byId('select-all').onclick = function() {
View
@@ -0,0 +1,15 @@
+(function() {
+ 'use strict';
+
+ importScripts('../dist/htmlminifier.min.js');
+ var minify = require('html-minifier').minify;
+ addEventListener('message', function(event) {
+ try {
+ postMessage(minify(event.data.value, event.data.options));
+ }
+ catch (err) {
+ postMessage(err);
+ }
+ });
+ postMessage(null);
+})();

0 comments on commit 24a2925

Please sign in to comment.