• In-Page Script Modules

    From Lawrence D'Oliveiro@21:1/5 to All on Thu Feb 15 08:34:10 2024
    You can put a “<script type="module">” section directly in a web page.
    But what does that do? It does two things:

    * Enable strict mode on that script section
    * Defer execution of that script section until the page has loaded.

    What it doesn’t do:

    * Turn the script section into a module.

    You could say it does turn the code into a module, with its own global namespace. But this module has no name, so there is no way to import
    anything from it into other code on the page. Or is there?

    It turns out you can export things from this module, by attaching them
    to the global “window” object. Here’s an example, where I create a pretend-module called “inpage” that contains the objects exported from
    my in-page module:

    <script type="module">
    function doit(spanid)
    {
    document.getElementById(spanid).innerHTML += "Hi There.<br>\n"
    } /*doit*/

    window.inpage = {"doit" : doit}
    </script>

    That only contains a single object, but you can see how to add more in
    the same way.

    Now, elsewhere on the page, I can access the contents of this module
    quite easily, e.g.

    <p>Something should appear here → <span id="content"></span> ← watch this space.
    <button onclick="inpage.doit(&quot;content&quot;)">Click Me</button>

    --- SoupGate-Win32 v1.05
    * Origin: fsxNet Usenet Gateway (21:1/5)