WillemvanderVeen WillemvanderVeen - 3 years ago 161
HTML Question

Maintain a html header using JS/JQuery

Working on a website, want to use the same header on each page.
I am first trying it out by loading the files from my files system into the browser however this gives a problem with the following code (got it in this link):

code:



<html>
<head>
<title></title>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>

<script>
$(function(){
$("#header").load("header.html");
$("#footer").load("footer.html");
});
</script>

</head>
<body>
<div id="header"></div>
<!--Remaining section-->
<div id="footer"></div>
</body>
</html>


This doesn't seem to work, I read in the comments that this doesn't work anymore because of safety reasons.

Question:



Is there another way to solve this problem using Javascript/JQuery?

Answer Source

function getUrl(url) {
    return new Promise((resolve) => {
        let XHR = ("onload" in new XMLHttpRequest()) ? XMLHttpRequest : XDomainRequest;
        let xhr = new XHR();

        xhr.open('GET', url, true);

        xhr.onload = function() {
            resolve(this.responseText);
        };

        xhr.send();
    });
}

let header = document.querySelector('#header');
let footer = document.querySelector('#footer');

getUrl('header.html')
    .then(
        resolve => header.innerHTML = resolve
    );
    
getUrl('footer.html')
    .then(
        resolve => footer.innerHTML = resolve
    );

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download