Q:

How to optimize the web speed of a Leaflet map

I'm trying to optimize the speed of a web page, where a Leaflet map is included. According to GTMetrix and Google PageSpeed Insight, I should:

Optimize the following images to reduce their size [several images served from 'https://services.arcgisonline.com/ArcGIS/rest/services/...'], serving them in next-gen formats
Defer parsing of the JavaScript https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.4.0/leaflet.js
Serve 'leaflet.js' and 'leaflet.css' inline

I would appreciate any similar experiences optimizing Leaflet maps. Is it worth serving JS and CSS of Leaflet inline? Can I modify the code to call 'arcgisonline.com' images in other lighter formats?
The code of my simple webpage
<link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.4.0/leaflet.css'>
<script src='https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.4.0/leaflet.js'></script>
<div id='myMap' style='height:700px;width:700px;'></div>
<script>
var map = L.map('myMap').setView([51.505, -0.09], 13);
L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', {maxZoom: 19, attribution: 'Tiles &copy; Esri &mdash; Source: Sources: Esri, DigitalGlobe'}).addTo(map);L.tileLayer('https://services.arcgisonline.com/ArcGIS/rest/services/Reference/World_Boundaries_and_Places/MapServer/tile/{z}/{y}/{x}', {maxZoom: 19}).addTo(map);
L.tileLayer('https://services.arcgisonline.com/ArcGIS/rest/services/Reference/World_Transportation/MapServer/tile/{z}/{y}/{x}', {maxZoom: 19}).addTo(map); L.marker([51.505, -0.09]).addTo(map);
</script>

Thank you very much.

A:

Most of the speed "optimizations" you refer to are general to webpages, there is little specific to Leaflet in particular.
Deferring is usually approached by simply placing your JS (including the Leaflet script tag) just before the end of your page body, so that it does not delay rendering of the rest of your HTML.
You can implement true deferring but then it becomes more complex ensuring your script executes after Leaflet is done loading; the easiest would be in that case to indeed inline Leaflet JS together with your script. But then you lose the potential cache of Leaflet asset, in case your visitor had browsed to other websites which have used these exact same assets.
In the case of Leaflet, you can also use a "skeleton" as a placeholder for your map, so that your visitor sees a static image while Leaflet and your script are loading. Make sure you have the right to host the static image.

