0
votes

I have a question about optimally integrating leaflet into the HTML document.

I have read this: Where should I put <script> tags in HTML markup?

If I interpret this information correctly, then if possible, you should include JavaScript with the attribute async or defer. And if possible you should put the Js-files into the -element.

The Leaflet.js must be fully loaded for a map to be displayed. Therefore, I can not use the attribute "async". But I can use the attribute "defer". The best place for integrating the leaflet.js is the -element.

After that I have to integrate my individual JavaScript code with the defer-attribute, so that it executes after leaflet.js.I have to put this js-file after the div that holds my map.

Is this correct or could there be a problem with using defer and is there a better place to integrate the js-files?

I ask this question, because I do not see this attributes async or defer in the examples on the website http://leafletjs.com/examples/.

Thank you for an answer.


This is my example code that runs without error:

<html>
  <head>
    <title>Eine OSM Karte mit Leaflet</title>
    <link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css" />
  </head>
<body>
<script src="https://unpkg.com/[email protected]/dist/leaflet.js" defer></script>
  <div id="map" style="width: 600px; height: 400px"></div>
  <script src="mymap_99.js" defer></script>
</body>
</html>

Where the file mymap_99.js is a short test map:

var map = L.map('map',
{
  center: [50.27264, 7.26469],
  zoom: 10
});
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png').addTo(map);

Crossposting: https://groups.google.com/forum/#!topic/leaflet-js/fRC9ElCtFaY

1

1 Answers

2
votes

You’re right in that your second script depends on the first being loaded but that does not mean you can’t use async.

if you wait for the load event to fire, you can be sure the leaflet library has loaded before trying to use it:

<html>
  <head>
    <title>Eine OSM Karte mit Leaflet</title>
    <link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css" />
    <script src="https://unpkg.com/[email protected]/dist/leaflet.js" async></script>
  </head>
<body>
  <div id="map" style="width: 600px; height: 400px"></div>
  <script>
  window.addEventListener('load', function() {
    var map = L.map('map',
      {
        center: [50.27264, 7.26469],
        zoom: 10
      }
    );
    L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png').addTo(map);
  }, false);
  </script>
</body>
</html>

I think if at all possible it’s better to use async than defer (because async scripts give the browser more flexibility for when to load and when to execute). In this case you could use async for both scripts (provided you wait for the load event before drawing the map).