rschroll / efm

Epub for Monocle — A pure javascript implementation of the book data interface for Epub2 and Epub3
http://rschroll.github.com/efm
44 stars 15 forks source link

EFM - Epub for Monocle

Epub for Monocle is a pure Javascript implementation of Monocle's book data interface for Epub2 and Epub3 files. This means that you can use Monocle to load Epub files in a completely client-side manner.

See it in action, and check out this branch to see how EFM is deployed.

Usage

EFM uses the zip.js library for unzipping the Epub files, so you'll need that. And of course, you need Monocle to actually display the ebook in your browser.

EFM provides a Epub object, which implements the book data interface. It takes two arguments for its constructor: the Epub file as an HTML5 file object and a callback to be called when the Epub object has been initialized. The callback is necessary because the zip.js library works asynchronously, so the parsing of the Epub file will not be done until after the Epub object is constructed.

Thus, if we have a file input with id="file" and a div with id="reader" for the Monocle reader, the simplest code to render the Epub file selected in the file input is

var file = document.getElementById("file").files[0];
new Epub(file, function (bookData) {
    Monocle.Reader("reader", bookData);
});

With a modern browser on a modern machine, EFM is reasonably snappy. I can load Moby Dick in under 1 second on my laptop, for example.

Working with remote Epub files

EFM is designed to work with local files, since Monocle is designed for working with remote files. But instead of dealing with the remote Epub file directly, Monocle trusts that you will convert it to a book data object on the server. This is much better than doing the conversion on the client with EFM, since the server has known capabilities, the server is generally more powerful than the clients, and this doesn't require the client to download as much javascript. If you're worried about the impact on the server, you can always do the conversion offline and upload the unzipped Epub file and the book data object to the server. This means that no conversion is needed whenever a client requests the book. Think of all the electrons you'll save!

That said, it is possible for EFM to work with remote Epub files. The first argument of the Epub object can be a HTML5 blob object, rather than a file object. Conveniently, an XMLHttpRequest can be made to return a blob. Thus, the simplest code to display a remote Epub file is

var request = new XMLHttpRequest();
request.open("GET", "url/of/file.epub", true);
request.responseType = "blob";
request.onload = function () {
    new Epub(request.response, function (bookData) {
        Monocle.Reader("reader", bookData);
    });
};
request.send();

But before you do this, please think long and hard if there isn't a better way. Think of the electrons!

Implementation Notes

License

EFM is distributed under the MIT license.