今日已更新 184 条资讯 | 累计 29326 条内容
关于我们

Processing 100MB PDFs in the Browser: The Performance Optimizations That Made TinyPDF Usable

nikoo li 2026年07月28日 23:35 6 次阅读 来源:Dev.to

Processing 100MB PDFs in the Browser: The Performance Optimizations That Made TinyPDF Usable When I built TinyPDF ( https://tinypdf.cn/?utm_source=devto&utm_medium=blog&utm_campaign=performance_optimization&utm_content=devto_performance_2026-07-28 ), I had one hard rule: no backend. Everything had to run in the browser. No file uploads, no servers, no costs. Just drag, drop, compress, download. But when I tested the first version with a real portfolio—88MB, 45 pages, full of high-res images—it froze the tab for 12 seconds. Here's what I changed to get that down to 2 seconds, without losing any features. 1. Use Web Workers for PDF Parsing (Don't Block the Main Thread) The first mistake: I ran PDF.js parsing directly on the main thread. // ❌ Bad: Blocks UI while parsing const pdf = await pdfjsLib . getDocument ( arrayBuffer ). promise ; The fix: Offload everything to a Web Worker. The main thread only handles user input and progress updates. // ✅ Good: Web Worker does the heavy lifting // Main thread const worker = new Worker ( ' pdf-compressor.worker.js ' ); worker . postMessage ({ type : ' process ' , data : arrayBuffer , targetSizeMB : 2 }); worker . onmessage = ( e ) => { if ( e . data . type === ' progress ' ) updateProgress ( e . data . percent ); if ( e . data . type === ' done ' ) downloadBlob ( e . data . blob ); }; Result: Tab stays responsive even with 100MB files. 2. Stream Image Processing (Don't Load All Pages Into Memory) Second mistake: I loaded every page into memory at once before processing. For a 45-page portfolio, that's 45 full-res images in memory simultaneously. The fix: Process one page at a time, and stream results to the output blob incrementally. // ✅ Good: Process one page, free memory, repeat for ( let i = 1 ; i <= numPages ; i ++ ) { const page = await pdf . getPage ( i ); const viewport = page . getViewport ({ scale : 1 }); const canvas = document . createElement ( ' canvas ' ); canvas . width = viewport . width ; canvas . height = view

本文内容来源于互联网,版权归原作者所有
查看原文