What's the Best Way to Efficiently Store Binary Data in a JavaScript File?

May 1, 2025 5 answers
Asked by ..reconsider
I'm trying to minimize the size of my JavaScript file while embedding some binary data into it. Are there any methods that are more efficient than base64? Ideally, I want to store the data byte-for-byte without unnecessary bloat.

Answers

park bench philosopher
If you really need to embed data directly in your JavaScript file, base64 is pretty much your best option. You could theoretically create a custom base encoding with a different character set, but honestly, that's a bit over the top. Remember, JavaScript files are plain text (usually UTF-8), so you're better off storing binary data in separate files and loading them in as needed.
Reply to this answer
..reconsider
Reply to this answer
11.kHz.filter
You might consider adding a layer of compression depending on your data. For example, you could compress your binary data with something like zip or RLE, then encode it as base64 or an ArrayBuffer. Just keep in mind that you'll have to weigh the additional space used by compression methods against any savings they provide.
Reply to this answer
drain.cover
Might I suggest reconsidering your approach? Depending on the MIME type for serving JavaScript files, you might be inadvertently hindering your efforts to save space. If you can, store the binary data in separate files and load them using fetch or XMLHttpRequest. There are also bundlers that can handle loading binary files directly.
Reply to this answer
!lock the casters
Why not just go for an ArrayBuffer? It's a great way to handle binary data.
Reply to this answer

Add your answer

Answers are reviewed before publication.

Related Discussions