Philipp S.
Philipp S.

Reputation: 981

Leaflet: Lazy load mapbox tiles

How can I lazyload map tiles when using Leaflet?

Especially on mobile devices I don't want to load maptiles at the beginning because most of my users never scroll down to the map.

Upvotes: 1

Views: 3696

Answers (2)

Sergey Sipatov
Sergey Sipatov

Reputation: 19

L.tileLayer(this.settings.tiles + '/{z}/{x}/{y}.jpg', {...})
    .on('tileloadstart', function(event) {
        event.tile.setAttribute('loading', 'lazy');
    });

Upvotes: 1

ghybs
ghybs

Reputation: 53185

Well, a very simple trick would be to create your map, or at least to add your Tile Layer, only when your map container comes into viewport.

That way, the tiles will not be requested before the map is actually viewable.

As to how to know when this situation happens, you should find plenty resources online and here. Basically you compare the document scroll and the map container position, and listen to scroll event. A more recent solution uses Intersection Observer.

Upvotes: 2

Related Questions