Make And Use A JavaScript Module Directly Inside A Single HTML File
I like writing completely self contained files in my notes that publish and work directly on my site without additional build steps or processing. I'm also moving more and more to using JavaScript modules for things. It took a bit to figure out how to combine those two since modules usually come as separate files.
Here's what I'm doing :
Details
-
The first [TODO: Code shorthand span ] tag contains the code for the module
-
Browsers don't try to execute [TODO: Code shorthand span ] tags when the [TODO: Code shorthand span ] attribute is set to [TODO: Code shorthand span ] . So, the first tag doesn't do anything directly
-
The second [TODO: Code shorthand span ] tag is a regular module
-
Instead of loading a module from a separate file it uses [TODO: Code shorthand span ] to simulate a new file to load from
-
The [TODO: Code shorthand span ] content from the first script is included in a [TODO: Code shorthand span ] which gets assigned a type of [TODO: Code shorthand span ] and fed into the [TODO: Code shorthand span ]
-
When all of that is passed to [TODO: Code shorthand span ] it acts the same as if an external file was used and the contents of the first [TODO: Code shorthand span ] tag get loaded as a module
-
Check the console and you'll see the "This is from the inline module" output from calling [TODO: Code shorthand span ]
With all that in place I can write a single file that includes the module directly. I really like the approach.
Footnotes And References
- •
- •
- •
- •