0

How do I access variables from the first script in the second script — in this case, map?

I can’t do this in a single script because:

  • The first script must be of the module type; without it, import does not work.
  • The second script cannot be of the module type, because the function inside must be visible in HTML. (The functions in the module script are not visible.)

Map loading script:

<script type="module">
    import { Map, NavigationControl, Marker, LngLatBounds } from 'https://cdn.skypack.dev/maplibre-gl';

    var map = new Map({
        container: 'map',
        center: [ myLatLng.lng, myLatLng.lat ],
        zoom: 13
    });
</script>

Another script in the same file:

<script>
    function setReaction(reactionNumber) {
        // code
    }
</script>
Sebastian Simon
  • 14,320
  • 6
  • 42
  • 61
DevNet
  • 41
  • 4
  • 2
    _“because the function inside must be visible in HTML”_ — No, they don’t need to be. Using ` – Sebastian Simon May 06 '21 at 09:27
  • Use [event delegation](//developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events#Event_delegation) instead of assigning multiple events — it’s more maintainable, and applies to dynamically added elements. E.g., use an [event argument](//developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#The_event_listener_callback)’s [`target`](//developer.mozilla.org/en-US/docs/Web/API/Event/target). See [the tag info](/tags/event-delegation/info) and [What is DOM Event delegation?](/q/1687296/4642212). – Sebastian Simon May 06 '21 at 09:27

1 Answers1

0

script with a type=module are "incapsulated" and all variable declarations are not assigned automatically to the Window object.

You can assign it by your self,

<script type="module">
    import { Map, NavigationControl, Marker, LngLatBounds } from 'https://cdn.skypack.dev/maplibre-gl';

    window.map = new Map({
        container: 'map',
        center: [myLatLng.lng, myLatLng.lat],
        zoom: 13
    });
</script>

But, pay attention that the browser is not assuring any thing between scripts type=module which uses import and other ones, this means that in your case you need to "wait" till the remote import finishes and then run your code which is depended on the import result.

In the example below, I've used the import() syntax which returns a Promise, this Promise I assign to be on the global Window object, and you function should use it.

<button onclick="checkMap()" type="button">Test</button>

<div id='map'></div>
<script type="module">

window.mapResolver = import('https://cdn.skypack.dev/maplibre-gl').then(
  ({ Map, NavigationControl, Marker, LngLatBounds }) => {
    var map = new Map({ container: 'map', center: [0, 0], zoom: 13 });

    return map;
  }
);

</script>

<script>
  function checkMap() {
    window.mapResolver.then((map) => {
      console.log(map)
    })
  }
</script>
felixmosh
  • 20,379
  • 4
  • 36
  • 56