0

I tried to put <header> and <footer> in external files. In the console, the code outputs fine, but then the code returns undefined.

Footer HTML:

<footer id="footer" class="footer mt-auto py-3 bg-light">
<div class="container">
    <div class="col-12 text-center">
        <a style="text-anchor: middle">© 2021 AlexInCube</a>
    </div>
</div>

main.html

<script>document.write(importHTMLdata("content/basement.html"))</script>

scripts.js

function importHTMLdata(path){
    $.get(path, function(html_string)
    {
        console.log(html_string)
        return html_string;
    });
AlexInCube
  • 69
  • 6
  • document.write override existing texts so not good to use – Rana Sep 14 '21 at 14:56
  • https://stackoverflow.com/q/54924823/16846346 try to take a reference from this – Rana Sep 14 '21 at 14:57
  • @Rana it's "ok" if it's used inline like here, it won't overwrite anything. By "ok", I mean it works as expected, certainly not recommended. However `$.get` is asynchronous, which is OPs problem, so there's nothing write at the time it tries. – freedomn-m Sep 14 '21 at 15:00

1 Answers1

0

It is NOT recommended to have document.write - it will wipe the page if executed after page load.

Just have this in your js file

$(function() { // on page load
  const importHTMLdata = path => { // define a function taking a path
    $.get(path, function(html_string) { // get the path
      $("body")[path.indexOf("footer") != -1 ? "append" : "prepend"](html_string); // if footer call $("body").append, if not call $("body").prepend
    });
  }
  importHTMLdata("content/header.html"); // load header
  importHTMLdata("content/footer.html")  // load  footer
});
<script src="scripts.js"></script>
mplungjan
  • 169,008
  • 28
  • 173
  • 236