0

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?

Willem van der Veen
  • 19,609
  • 11
  • 116
  • 113
  • 3
    It should work if you're loading the file from a server, it won't work if you're loading from a local file. – Barmar Sep 29 '17 at 22:59
  • javascript? pah! jquery? boo! all you need it copy and paste. Its been round for thousands of years and will out live all the latest fads...all you really need is ctrl+f, crtl + c and crl+v. boom. what about if i have to update it in the future? Find and replace. Job done. – Rob Wilson Sep 29 '17 at 23:00
  • 2
    @RobWilson That means that every time you change one of the files you have to copy and paste it into hundreds or thousands of other files. – Barmar Sep 29 '17 at 23:00
  • @Barmer - hundreds and thousands? really? well who cares? find and replace. Boom! – Rob Wilson Sep 29 '17 at 23:02
  • But consider to do this Server side! There are plenty of static site generators out there! – Lux Sep 29 '17 at 23:09
  • 1
    * whispers * _PHP_ – SourceOverflow Sep 29 '17 at 23:12
  • I agree with @SourceOverflow because PHP is server-side, so you don't have that lag after you load from having to wait for JS, and it's more straight-forward being on the server. – clabe45 Sep 29 '17 at 23:16

1 Answers1

0

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
    );
zhuravlyov
  • 483
  • 2
  • 10