Make header and footer files to be included in multiple html pages

前端 未结 11 2068
無奈伤痛
無奈伤痛 2020-11-22 06:49

I want to create common header and footer pages that are included on several html pages.

I\'d like to use javascript. Is there a way to do this using only html and

11条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-22 07:33

    I've been working in C#/Razor and since I don't have IIS setup on my home laptop I looked for a javascript solution to load in views while creating static markup for our project.

    I stumbled upon a website explaining methods of "ditching jquery," it demonstrates a method on the site does exactly what you're after in plain Jane javascript (reference link at the bottom of post). Be sure to investigate any security vulnerabilities and compatibility issues if you intend to use this in production. I am not, so I never looked into it myself.

    JS Function

    var getURL = function (url, success, error) {
        if (!window.XMLHttpRequest) return;
        var request = new XMLHttpRequest();
        request.onreadystatechange = function () {
            if (request.readyState === 4) {
                if (request.status !== 200) {
                    if (error && typeof error === 'function') {
                        error(request.responseText, request);
                    }
                    return;
                }
                if (success && typeof success === 'function') {
                    success(request.responseText, request);
                }
            }
        };
        request.open('GET', url);
        request.send();
    };
    

    Get the content

    getURL(
        '/views/header.html',
        function (data) {
            var el = document.createElement(el);
            el.innerHTML = data;
            var fetch = el.querySelector('#new-header');
            var embed = document.querySelector('#header');
            if (!fetch || !embed) return;
            embed.innerHTML = fetch.innerHTML;
    
        }
    );
    

    index.html

    
    
    

    views/header.html

    
    

    The source is not my own, I'm merely referencing it as it's a good vanilla javascript solution to the OP. Original code lives here: http://gomakethings.com/ditching-jquery#get-html-from-another-page

提交回复
热议问题