2

I have a JavaScript module mymmodule.js exporting a list:

export var mylist = ['Hallo', 'duda'];

Normally this module is used in other modules and this works fine. But additionally I want to use the export(s) of the module as-is in an inline script on an HTML page. I tried to copy the exports to the window object:

<html>
<head>
    <script type="module">import * as mm from './mymodule.js';  window.mm = mm;</script>
</head>

<h1>MyMain</h1>
<p>
    <div id = "info">...</div>
</p>

<script type="text/javascript">
    document.getElementById('info').textContent = window.mm.mylist;
</script>            
</html>

but I get the error "window.mm is undefined" in the console. I tried referencing mm.mylist instead of window.mm.mylist with no better result.

How can I reference the exports of a module in a second inline script on the HTML page?

1 Answer 1

4

The problem is that modules are execute at the same stage as pscripts with the defer attribute](https://javascript.info/script-async-defer#defer), i.e. after reading the page and executing JavaScript in script tags.

Therefore, when the browser sees

document.getElementById('info').textContent = mm.mylist

the mymodule.js script hasn't been executed and the mm object is not available yet.

To mitigate this you need to run code referencing exports from mymodule after the DOM is completely loaded, e.g. in the onload event:

<html>
<head>
    <script type="module">import * as mm from './mymodule.js';  window.mm = mm;</script>
</head>

<h1>MyMain</h1>
<p>
    <div id = "info">...</div>
</p>

<script type="text/javascript">
    window.onload = function() {
        document.getElementById('info').textContent =    mm.mylist;
    }
</script>            
</html>
Sign up to request clarification or add additional context in comments.

Comments

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.