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

Network requests made before cache check, preventing true offline-first behavior #407

Open
matzflander opened this issue Oct 30, 2024 · 0 comments
Labels

Comments

@matzflander
Copy link

Current Behavior

When using the offline tile layer with useCache: true and useOnlyCache: true, network requests are still made for tiles before checking the cache. This happens because in the createTile method, super.createTile is called first, which initiates the network request immediately, before the cache is checked.

This issue was discovered during implementation of an offline-first map solution.

Expected Behavior

For a true offline-first approach:

  1. Check cache first
  2. If tile exists in cache and isn't expired, use it without making a network request
  3. Only make network request if tile isn't in cache or is expired

Code Analysis

Current implementation in TileLayer.js:

createTile(coords, done) {
    const tile = super.createTile(coords, done);  // Network request starts here
    if (this.options.useCache) {
        this._db.get(this._getStorageKey(coords), (err, data) => {
            if (data && !err) {
                this._setDataTile(tile, data);
            }
            // ...
        });
    }
    return tile;
}
Impact
This causes unnecessary network requests even when tiles are cached, and results in error logs in the console when offline, even though the cached tiles are eventually displayed.
Suggested Solution
Modify the createTile method to check cache before initiating any network requests:
jsCopycreateTile(coords, done) {
    const tile = document.createElement('img');
    if (this.options.useCache) {
        this._db.get(this._getStorageKey(coords), (err, data) => {
            if (data && !err) {
                this._setDataTile(tile, data);
                done(null, tile);
            } else {
                // Only make network request if cache miss
                return super.createTile(coords, done);
            }
        });
    } else {
        return super.createTile(coords, done);
    }
    return tile;
}
Environment

leaflet.offline version: 3.1.0
Browser: Latest versions of Chrome/Firefox/Safari
OS: Windows/Mac/Linux
@allartk allartk added the bug label Oct 30, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants