Make And Use A JavaScript Module Directly Inside A Single HTML File
April 2024
Introduction
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
scripttag contains the code for the module -
Browsers don't try to execute
scripttags when thetypeattribute is set totext/template. So, the first tag doesn't do anything directly -
The second
scripttag is a regular module -
Instead of loading a module from a separate file it uses
.createObjectURL()to simulate a new file to load from -
The
.innerTextcontent from the first script is included in aBlobwhich gets assigned a type ofapplication/javascriptand fed into the.createObjectURL() -
When all of that is passed to
await import()it acts the same as if an external file was used and the contents of the firstscripttag get loaded as a module -
Check the console and you'll see the "This is from the inline module" output from calling
ping()
With all that in place I can write a single file that includes the module directly. I really like the approach.
end of line