如何优化 Leaflet 地图的网络速度

How to optimize the web speed of a Leaflet map

我正在尝试优化包含传单地图的网页的速度。根据 GTMetrix 和 Google PageSpeed Insight,我应该:

  1. 优化以下图片以减小它们的大小[从“https://services.arcgisonline.com/ArcGIS/rest/services/...”提供的几张图片],以下一代格式提供它们
  2. 延迟解析 JavaScript https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.4.0/leaflet.js
  3. 内嵌 'leaflet.js' 和 'leaflet.css'

如果有任何类似的优化 Leaflet 地图的经验,我将不胜感激。是否值得为 JS 和 Leaflet 内联 CSS 提供服务?我可以修改代码以调用其他较轻格式的 'arcgisonline.com' 图像吗?

我的简单网页代码

<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>

非常感谢。

你说的速度"optimizations"大部分是网页通用的,没有什么特别针对Leaflet的。

延迟通常是通过简单地将您的 JS(包括 Leaflet 脚本标记)放在页面主体的末尾之前来实现的,这样它就不会延迟其余部分的呈现 HTML。

您可以实现真正的延迟,但这样会变得更加复杂,确保您的脚本在 Leaflet 加载完成后执行;在这种情况下,最简单的方法就是将 Leaflet JS 与您的脚本一起内联。但是,如果您的访问者浏览到使用了这些完全相同资产的其他网站,那么您将失去 Leaflet 资产的潜在缓存。

对于 Leaflet,您还可以使用 "skeleton" 作为地图的占位符,以便访问者在加载 Leaflet 和脚本时看到静态图像。请确保您有权托管静态图片。

这已经很老了,对于您的问题可能有点笼统,但关于地理数据:

  • 您应该减少加载的数据量(即您真的需要所有观察结果吗?)
  • 如果您使用多边形,您应该简化几何图形。令人难以置信的 mapshaper 为您的速度做了很多。您可以使用它,例如在 R 中使用 rmapshaper 包来预处理你的数据。
  • 您可以考虑使用矢量图块并在后端和前端之间实现一个 tileserver,为不同的缩放级别预加载数据(use.e.g. geoserver) or alternatively tile the data dynamically inside your database (postgis is able to do that with st_AsMV()) and serve tiles to your leaflet interace which then needs a plugin 为基于服务器的服务器创建动态请求在地图的当前边界框上 或者使用支持在前端平铺的 webmapframework(例如 openlayers)。