Skip to content

Instantly share code, notes, and snippets.

@coder0107git
Last active August 20, 2023 03:05
Show Gist options
  • Save coder0107git/1df781b4747be12a742bcd7896ed2693 to your computer and use it in GitHub Desktop.
Save coder0107git/1df781b4747be12a742bcd7896ed2693 to your computer and use it in GitHub Desktop.
Inline Modules in HTML

Inline modules

Why?

Recently I have found myself using various methods to inline modules for various reasons. I usually would embeded a data url but found that it wasn't flexible enough. So this is what I came up with.

Code

window.inlineModules = {};

const inlineModules = document.querySelectorAll("script[type='text/javascript+inlineModule']");

inlineModules.forEach(module => {
    window.inlineModules[module.getAttribute("data-fileName")] = 
        URL.createObjectURL(
            new Blob(
                [ module.innerText ],
                {
                    type: "application/javascript"
                }
            )
        );
});

Usage

<script type="text/javascript+inlineModule" data-fileName="greet.js">
function greet(name, greeting = "Hello") {
    return `${greeting} ${name}!`;
}

export default greet;
</script>

Example

<script type="module">
const greet = await import(window.inlineModules["greet.js"]);

const name = prompt("What Is Your Name?");

alert(greet(name));
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment