1

Normally when you import a script in a traditional way, you do something like:

<script src="https://jsdeliver.com/packagename"></script>

And when you import a ES module, you do:

<script>
import { method } from "https://jsdeliver.com/packagename"
...
</script>

I was wondering if there's a way to write a JS library once, so that it will automatically load in both ways. If you import, it would load as ES module, and if you include it as <script src> it loads as traditional script.

1 Answer 1

2

Yes and No.

You can write an ESM module that can be loaded both from other ESM modules with import and can be loaded from a <script> tag. To do that, however, you must use the type="module" attribute in the script tag as in:

<script type="module" src="https://jsdeliver.com/packagename"></script>

This tells the browser that this is a Javascript module script, not the older fashioned plain browser script.


You cannot have a script that is both a module and a traditional browser script because an ESM module script like you show has exports and you can't have those in a traditional, plain browser script.

So, you have to make the script an ESM script and then use the proper modifier in the <script> tag so the browser will load the ESM script properly.


Note, the situation you show would not be very common because this line of code:

import { method } from "https://jsdeliver.com/packagename"

implies that a primary purpose of this module is to deliver exported functions, but loading that via a <script> tag would not be delivering those exports. So, the script would have to have two somewhat different purposes when loaded the two different ways. Doable, but perhaps not really how you should do things. Perhaps you would instead, put the common, shared code into its own ESM module that can be shared and then let the top level module serve the different purposes that a <script> tag would vs. a script that you were importing methods from.

Sign up to request clarification or add additional context in comments.

3 Comments

I wonder if the server could distinguish these through the Accept header sent by the browser?
@Bergi - do you mean, so that it could serve something different? Why not just use different urls for the different purposes?
I was just wondering whether it would be possible, not saying it's a good idea.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.