Inject HTML snippet from file

andrewelans

Andrew Elans

Posted on November 5, 2024

Inject HTML snippet from file

A question on stackoverflow:

Include another HTML file in a HTML file

I was playing around and came up with a clean way to do it with:
1) Reading a content of the file with fetch()
2) Rendering a DOM Node from string
3) Replacing <script> tag with the DOM Node in place.

Removing the <script> tag is mentioned in the HTML spec para 4.12.1.1 Processing model so replacing seems to be in accordance with the specification.

Structure

Image description

Another HTML file

<!-- another-html-file.html -->
<h1>Another HTML file</h1>
Enter fullscreen mode Exit fullscreen mode

HTML file index.html

Script tag will be replaced in place with the content of another-html-file.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        (() => {
            const thisScript = document.currentScript
            fetch('./another-html-file.html')
            .then(
                (res) => (
                    res.ok // checking if response is ok
                    ? res.text() // return promise with file content as string
                    : null // return null if file is not found
                )
            )
            .then(
                (htmlStr) => (
                    htmlStr // checking if something is returned
                    ? thisScript.replaceWith(
                        // replace this script tag with the DOM Node created from string
                        document.createRange().createContextualFragment(htmlStr)
                    ) 
                    : thisScript.remove() // fallback to remove script if null is returned
                )
            )
        })()
    </script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Result

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>Another HTML file</h1>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
andrewelans
Andrew Elans

Posted on November 5, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related