Are loading a JavaScript ES6 module via <script src=""> and importing all exports in a <script> tag the same?
Asked Answered
U

1

8

Can't understand the difference between the two examples that I just read at the end of the Deno manual section on the deno bundle command:

Bundles can also be loaded in the web browser. The bundle is a self-contained ES module, and so the attribute of type must be set to "module". For example:

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

Or you could import it into another ES module to consume:

<script type="module">
  import * as website from "website.bundle.js";
</script>

I was under the impression that both forms achieve the same effect (i.e., "fetched and executed immediately, before the browser continues to parse the page"), and the latter is used when a script follows or one wants to narrow down what is imported (e.g., as seen in this answer).


This may be considered a duplicate of other questions (see bottom for the list) but those answers didn't help me much, and the ancillary sources also didn't seem to reveal if my assumption is correct. (On the other hand, it is more than possible that I overlooked something obvious and would have to work on my reading comprehension skills...)

Unsnap answered 4/4, 2021 at 22:52 Comment(2)
F
3

I was under the impression that both forms achieve the same effect

Yes, both of these will have the same effect

(i.e., "fetched and executed immediately, before the browser continues to parse the page"),

No, that any <script with type="module" will defer by default, so the loading will not block parsing. All deferred scripts are then executed in the order they appear, after parsing and before DOMContentLoaded fires.

and the latter is used when a script follows or one wants to narrow down what is imported (e.g., as seen in this answer).

Which one you want to use also depends on what work is done in the bundle. If the bundle only contains libraries, and doesn't create any side effects (ie, interacting with the page, rendering, etc) then you will probably want to import it so that you can use the functions.

If it does have side-effects (ie. a react app that renders to the DOM), and is self-contained, then just including the tag will be enough to get it started

Fideicommissum answered 4/4, 2021 at 23:11 Comment(1)
Thank you for the concise, yet thorough answer! Not sure how I missed that <script type="module" ...> tags are deferred by default but I'm glad you pointed it out.Unsnap

© 2022 - 2024 — McMap. All rights reserved.