Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

book.locations.generate() asynchronous replacement #1405

Open
darylkell opened this issue Jan 13, 2025 · 0 comments
Open

book.locations.generate() asynchronous replacement #1405

darylkell opened this issue Jan 13, 2025 · 0 comments

Comments

@darylkell
Copy link

darylkell commented Jan 13, 2025

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));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant