Skip to content

book.locations.generate() asynchronous replacement #1405

@darylkell

Description

@darylkell

book.locations.generate() is slow as it runs sequentially. On one book that takes 19.6 seconds to load, this was reduced on my machine down to 0.5 seconds.

Assuming ePub is the class imported by script tag or similar, instead of using book.locations.generate() you can use the following book.ready.then() code to load the sections asynchronously.

This would be a nice addition in lieu of or in addition to book.locations.generate() as virtually every browser unloads tabs on mobile devices, causing books to be reloaded again and again when the user shifts focus.

const book = ePub(file);  // instantiate by normal means
const rendition = book.renderTo("reader", {
    width: "100%",
    height: "100%"
});

book.ready.then(() => {
    book.locations.break = 1800;
    const sections = book.spine.spineItems.filter(section => section.linear);

    // process the sections asynchronously rather than sequentially
    await Promise.all(sections.map(section => book.locations.process(section)));

    // update the book with some necessary information that .generate() does
    book.locations.total = book.locations._locations.length - 1;
    if (book.locations._currentCfi) {
        book.locations.currentLocation = book.locations._currentCfi;
    };
    
     // since we performed the process virtually in parallel, we must get the locations back in order
    const cfi = new ePub.CFI();
    book.locations._locations.sort((a, b) => cfi.compare(a, b));
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions