Created
February 28, 2018 14:00
-
-
Save hemkaran/149150a7d74cfc11dee26723a983f40e to your computer and use it in GitHub Desktop.
This file demonstrate using web worker to compress the data at frontend side (step 4)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Called when worker will be initialized | |
* @param worker | |
*/ | |
function workerInitialized (worker) { | |
// This will be called when worker finished compressing data. you can access data at e.data | |
worker.onmessage = function (e) { | |
console.log(e.data); | |
sendData(e.data); | |
}; | |
// Lets wait for the document to be ready, so that we will enought data to send | |
$(document).ready(function () { | |
// Let's create a lot of data to test the compression | |
var aLongString = '', | |
dataToSend; | |
for (var i = 0; i < 1000; i++) { | |
aLongString = aLongString + JSON.stringify(window.performance); | |
} | |
dataToSend = { | |
name: 'Hemkaran Raghav', | |
value: aLongString | |
}; | |
// Since data is ready, will be send two calls: | |
// 1. One call without compressing the data | |
sendData(dataToSend); | |
// 2. Second call after worker will compress our data | |
worker.postMessage({ | |
id: 1, | |
data: dataToSend, | |
action: 'compress' | |
}); | |
}) | |
} | |
// Used by workerInitialized to send different data | |
function sendData (data) { | |
$.ajax({ | |
// This url is created using Postman (https://chrome.google.com/webstore/detail/postman/fhbjgbiflinjbdggehcddcbncdddomop?hl=en) | |
// mock server, to check how to create a mock server | |
// check here: https://www.getpostman.com/docs/postman/mock_servers/setting_up_mock | |
url: 'https://cf9d49d3-f0ce-4cf9-90c5-76ad542d1982.mock.pstmn.io/event', | |
type: 'POST', | |
data: data | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment