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)

11 Tips That Make You a Better Typescript Programmer

typescript

1 Think in {Set}

Type is an everyday concept to programmers, but it’s surprisingly difficult to define it succinctly. I find it helpful to use Set as a conceptual model instead.

#2 Understand declared type and narrowed type

One extremely powerful typescript feature is automatic type narrowing based on control flow. This means a variable has two types associated with it at any specific point of code location: a declaration type and a narrowed type.

#3 Use discriminated union instead of optional fields

...

Read the whole post now!

πŸ‘‹ Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay