Vue with Web Worker

Use web worker to handle slow functions in Vue

by Fourzero

HTML

<script id="worker1" type="javascript/worker">
	
  // This script won't be parsed by JS engines because its type is javascript/worker.
  self.onmessage = function(e) {
  	console.log('slow function started execution inside worker with parameter: ', e.data)
    // execute slow function
    var sum = 1;
    	for (let i = 1; i < 10000000000; i++) {
      	sum = sum + i;
      }
    console.log('DONE!!slow function finished inside worker with result: ' + sum)
    self.postMessage(sum);
  };
 
</script>


<div id="app">
    <p ref="message">{{message}}</p>
    <p >slowFunctionResult: {{slowFunctionResult}}</p>
    <button @click="click">Click</button>
    <button @click="click2">Click (Run in worker)</button>
</div>

Vue

var blob = new Blob([
  document.querySelector('#worker1').textContent
], { type: "text/javascript" })

// Note: window.webkitURL.createObjectURL() in Chrome 10+.
var worker = new Worker(window.URL.createObjectURL(blob));


new Vue({
  el: '#app',
  data: {
    message: 'xx',
    slowFunctionResult: ''
  },
  
  methods: {
  	click() {
      this.message = 'hello';
      console.log("slow function start")
    	this.slowFunction();
      console.log("slow function done")
      
      // the next tick won't happen until the slow function finished
    },
    
    click2() {
      this.message = 'hello';
    
      let that = this;
      worker.onmessage = function(e) {
        console.log("Received result from worker!: " + e.data);
        that.slowFunctionResult = e.data;
      }
    	// DOM should be updated before the slow function execution finished
    	worker.postMessage(this.message); // Start the worker.
    },
    
    
    slowFunction() {
    	var sum = 1;
    	for (let i = 1; i < 10000000000; i++) {
      	sum = sum + i;
      }
    }
  }
})