case
ADM Blog
1Oct/100

Read/Load files from ZIP in JavaScript

At work we do a lot of JavaScript applications that have little to no HTML files (beside the index), everything is generated by JavaScript and we have tons of .js files that load at runtime and to reduce the size we have to minify them and that is really hard to debug and watch in the browser if something goes wrong. So I've made this JavaScript class that comes to help. What can you do is Zip up all your assets (js, images, css) and use ZipLoader class to read the zip and unpack your resources whenever you need them. It's small (10KB), easy to use and quite fast considering the extraction is made by JavaScript.

1
2
3
4
5
6
7
8
9
10
   // loads and caches the zip file
   var loader = new ZipLoader('files.zip');
   // creates a style node in the document header and appends the style
   loader.LoadCSS('files.zip://style.css');
   // creates a script node in the document header and appends the script
   loader.loadScript('files.zip://jquery.js');
   // returns the file content
   var someFileYouNeed = loader.load("files.zip://myFile.txt");
   // returns the base64 encoded image usable as img source
   $("#logo").attr('src', loader.loadImage('files.zip://images/logo.png'));

The level of compression using zip surpasses the js and css minification in all the ways possible. For example, My current application has 79 files (js, and few css) and they all sum up to 924KB in size. Zipping all those 96 files using Ultra compression level gives me 1 file of 126 KB => 1 server request. That's something.

The best performance is made Opera (strangely), then Firefox, Crome, Safari and last IE (no surprise here, I was expecting it before I even started).

It's a V 1.0 that still needs some work and it doesn't work in IE because that stupid browser overrides the mime type and at first null character in the reading of the zip, the content ends. I will fix this eventually :) I will also include this as a jClass library soon.

Update: Fixed it so it works in IE as well. There is a performance issue still. Will fix that too.

Till then, HERE are the sources and a demo.

The zip in the demo is made using 7Zip with Ultra Compression level.

Happy codding.



Comments (0) Trackbacks (2)
  1. Hi, I need some simple unzip code for my application and would like to use a modified version of your archive.js, but I cannot find any remark about copy rights. Can I use your code and do I have to mention you or your blog?


Reply

( Cancel )

CommentLuv badge

*