Skip to content

Instantly share code, notes, and snippets.

@dirkakrid
Created April 13, 2017 14:13
Show Gist options
  • Save dirkakrid/ef215792718e4f354551de17f574020f to your computer and use it in GitHub Desktop.
Save dirkakrid/ef215792718e4f354551de17f574020f to your computer and use it in GitHub Desktop.
Embed compressed data in HTML

Let's create a file with some data:

echo "here is some data weeeeeeeeeeeeeeeeeeee" > data.tsv

Compress it, encode it with base64, and put it in a javascript variable:

(echo -n "var data = '"; gzip -c data.tsv | base64 -w0; echo -n "'") > data.js

Here's what it looks like now:

cat data.js
var data = 'H4sICCbBYlgAA2RhdGEudHN2AMtILUpVyCxWKM7PTVVISSxJVChPxQK4ABdVssMoAAAA'

In your HTML file, decode and decompress the original data:

<script src="pako.js"></script>
<script src="data.js"></script>
<script>
// The data variable is imported from "data.js".
var x = pako.ungzip(atob(data), {to: 'string'})
console.log(x) // "here is some data weeeeeeeeeeeeeeeeeeee"
</script>

You'll need to include pako.

You can create the pako.js file like this:

npm install -g browserify
npm install pako

browserify -r pako --standalone pako > pako.js
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment