javascriptbrowseres6-modules

how to programmatically determine, within the module, if javascript module was loaded via script src (not imported)


Suppose I have a module:

// module.js
export default function greet() { console.info( 'hello' ); }

If the module is loaded via:

<script type=module>
import greet from './module.js';
...
</script>

then I want the calling code to be able to invoke greet() on its own, without it being called automatically (the normal scenario).

However, if the module is loaded via:

<script type=module src="./module.js"></script>

then I want the module to invoke greet() immediately (as a side-effect of being loaded).

How can I accomplish this?


Solution

  • Unfortunately, this question has a similar answer to your previous one: it isn't possible.

    Modules may export things, but they aren't responsible for how (and which) do the importers use (of) them.

    Modules are created to be separate and reusable, even on the same page, without re-evaluation:

    The module's code evaluated once, then its exports are passed to every place that imports it.

    That design is good, but essentially makes impossible for a module to determine anything about its importers.


    On the other hand, the <script type="module"> syntax also wasn't designed for that: it's the way to signal the browser through HTML the main (aka. "top-level") module, that loads its dependecies (sub-modules) on its own.


    Partial solution:

    Make a single top-level module, that imports everything else and operates the page by "side effects", and avoid importing other modules by script tags. Moreover, I recommend you to avoid side effects in the non-top-level modules, and focus on exports instead.

    And if someone really wants to import your module from their HTML, they can still do this instead:

    <script type="module">
      import greet from './module.js';
      greet();
    </script>