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

流过昼夜 提交于 2020-05-16 22:30:47

问题


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?


回答1:


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>


来源:https://stackoverflow.com/questions/61797713/how-to-programmatically-determine-within-the-module-if-javascript-module-was-l

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!