LoaderWorker.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. /**
  2. * Web Worker to load large amounts of data without locking up the UI.
  3. *
  4. * @author n1474335 [n1474335@gmail.com]
  5. * @copyright Crown Copyright 2017
  6. * @license Apache-2.0
  7. */
  8. /**
  9. * Respond to message from parent thread.
  10. */
  11. self.addEventListener("message", function(e) {
  12. const r = e.data;
  13. if (r.hasOwnProperty("file")) {
  14. self.loadFile(r.file);
  15. }
  16. });
  17. /**
  18. * Loads a file object into an ArrayBuffer, then transfers it back to the parent thread.
  19. *
  20. * @param {File} file
  21. */
  22. self.loadFile = function(file) {
  23. const reader = new FileReader();
  24. let data = new Uint8Array(file.size);
  25. let offset = 0;
  26. const CHUNK_SIZE = 10485760; // 10MiB
  27. const seek = function() {
  28. if (offset >= file.size) {
  29. self.postMessage({"progress": 100});
  30. self.postMessage({"fileBuffer": data.buffer}, [data.buffer]);
  31. return;
  32. }
  33. self.postMessage({"progress": Math.round(offset / file.size * 100)});
  34. const slice = file.slice(offset, offset + CHUNK_SIZE);
  35. reader.readAsArrayBuffer(slice);
  36. };
  37. reader.onload = function(e) {
  38. data.set(new Uint8Array(reader.result), offset);
  39. offset += CHUNK_SIZE;
  40. seek();
  41. };
  42. seek();
  43. };