0

I'm trying to keep my nav in one html file rather than copying and pasting it into every file so I don't have to edit every file if I want to change something. I want to include the nav code into my files but nothing I've tried so far has worked the way I want it to. I would like to do this using only html/css/js, this is something that seems like there would be an easy way to do it because it's so practical in a lot of projects.

So far I've tried

object/iframe - Embedded the code into it's mini window, not the desired result.

javascript object.write - Deleted code already in file being imported to.

w3.includehtml - Works in firefox, but not chrome, I can't figure out why. Help with this would be appreciated as this seems like the best method.

php include- Didn't work, probably because I don't know php and most likely did something wrong, I'm open to it if someone could show me how or link a tutorial.

1 Answers1

0

create the component as a template, like:

nav.template.html

<template>
  <nav><!-- nav stuff here ... there has to be only one childNode of template because of how we will mount it, but you could change that -->
  <style scoped>/* you can style only nav content directly here if you like */</style>
  </nav>
</template>

Then, load that with javascript on domready, like:

site.js

document.addEventListener('DOMContentLoaded', function() { // there are more thorough, extensible ways of attaching to this event ..
    let el = document.querySelector('.nav-mount-point')
    // I'm doing to use axois, assuming you load it from a CDN or directly. You could also do this with plain AJAX, etc
    axios.get('path/to/nav.template.html')
      .then(res => {
        let dt = document.createElement('div')
        dt.innerHTML = res.data
        el.appendChild(dt.children[0].content.cloneNode(true))
      })
      .catch(e => console.error(e))
}, false);
roberto tomás
  • 4,435
  • 5
  • 42
  • 71