DEV Community

Andrew Elans
Andrew Elans

Posted on

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

Do your career a big favor. Join DEV. (The website you're on right now)

It takes one minute, it's free, and is worth it for your career.

Get started

Community matters

Top comments (0)

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay