A PDF editor moves a large file into a Web Worker to keep parsing off the main thread. The first message still pauses the interface: passing a buffer without a transfer list copies its bytes as part of structured cloning. For large files, that copy can be expensive.
Transferring an ArrayBuffer changes ownership instead. The worker receives the buffer, and the sender's buffer becomes detached. Its byteLength becomes zero. Plan for that ownership change before wiring it into a preview or export flow.
Transfer the file bytes
This example uses a module worker and reads a selected file into memory. Serve these files over HTTP from the same origin, rather than opening the HTML file directly.
<input id="file" type="file" accept="application/pdf">
<output id="status"></output>
<script type="module" src="./main.js"></script>
// main.js
const worker = new Worker('./pdf-worker.js', { type: 'module' });
const status = document.querySelector('#status');
worker.onmessage = ({ data }) => {
status.textContent = `Worker received ${data.byteLength} bytes`;
};
worker.onerror = () => {
status.textContent = 'Worker failed';
};
document.querySelector('#file').addEventListener('change', async (event) => {
const file = event.target.files[0];
if (!file) return;
const buffer = await file.arrayBuffer();
const originalSize = buffer.byteLength;
worker.postMessage({ buffer }, [buffer]);
console.log({ originalSize, remaining: buffer.byteLength });
});
// pdf-worker.js
self.onmessage = ({ data }) => {
const bytes = new Uint8Array(data.buffer);
// Pass bytes to your PDF parser here.
self.postMessage({ byteLength: bytes.byteLength });
};
The buffer must be reachable from the message as well as present in the transfer list. Listing an object for transfer does not automatically insert it into the payload. In this example the worker can access it as data.buffer.
The example reports byte length; it does not parse or validate the PDF. A real parser needs its own error handling and a way to return useful results. The file input's accept attribute is a picker hint, so validate actual input in the processing pipeline too.
Keep a source for a second operation
After postMessage, the main thread cannot reuse the transferred buffer for a download or another worker. The File object still represents the selected file, so the application can read it again when it needs another buffer. That read takes time and memory; measure it for your workload.
Another option is to make a copy before transfer:
const workerCopy = buffer.slice(0);
worker.postMessage({ buffer: workerCopy }, [workerCopy]);
// buffer remains usable here.
This preserves the original but creates another full-size allocation. For a large PDF, that can erase much of the memory benefit of transferring. Decide which component owns the bytes at each stage, especially when a user can open another file before the previous parse finishes.
Typed arrays are views over buffers. If several views share a buffer, transferring that buffer detaches it for all those views on the sending side. A view over a small region can also share a much larger backing buffer. When the worker should receive only that region, copy the relevant bytes into a separate buffer first and transfer that copy.
Measure the whole trip
A transfer avoids the structured-clone copy for the transferred buffer. It does not remove the cost of reading the file, parsing it, rendering pages, or copying a large result back to the main thread. A worker can also return an ArrayBuffer with its own transfer list when ownership should move back.
Measure file reading, message handoff, parsing, and result delivery separately. Test with a large document and with rapid file changes: a response from an older job should not replace the preview for a newer file. Attach a job ID to each request and ignore results that no longer match the active selection.
If the worker only needs to return a page count or a small set of form field names, send that small result rather than the complete input buffer. If the main thread needs the bytes again, make the return transfer explicit and avoid accessing them in the worker afterward.
References: MDN on transferable objects, Worker.postMessage, and Blob.arrayBuffer.
Top comments (0)