LHJ

I'm a FE developer.

html include

01 Jul 2020 » html

html include

html template를 사용하지 않고 include 하는 방법이다.
ajax 통신을 이용한 방법인 것 같다.

<!DOCTYPE html>
<html>
<script>
    function includeHTML() {
        var z, i, elmnt, file, xhttp;
        /*loop through a collection of all HTML elements:*/
        z = document.getElementsByTagName("*");
        for (i = 0; i < z.length; i++) {
            elmnt = z[i];
            /*search for elements with a certain atrribute:*/
            file = elmnt.getAttribute("w3-include-html");
            if (file) {
                /*make an HTTP request using the attribute value as the file name:*/
                xhttp = new XMLHttpRequest();
                xhttp.onreadystatechange = function() {
                    if (this.readyState == 4) {
                        if (this.status == 200) {elmnt.innerHTML = this.responseText;}
                        if (this.status == 404) {elmnt.innerHTML = "Page not found.";}
                        /*remove the attribute, and call this function once more:*/
                        elmnt.removeAttribute("w3-include-html");
                        includeHTML();
                    }
                }
                xhttp.open("GET", file, true);
                xhttp.send();
                /*exit the function:*/
                return;
            }
        }
    };
</script>

<body>

<div w3-include-html="content.html"></div>
<footer w3-include-html="footer.html"></footer>
<script>
    includeHTML();
</script>

</body>
</html>
<div>
    <span>footer.html</span>
</div>
<div>
    <span>content.html</span>
</div>