Home > Mobile >  How should I display header and footer on other than 'Home' page?
How should I display header and footer on other than 'Home' page?

Time:11-24

Should I do traditional copy paste the header and footer on every page, or is there any way that I can display it using JavaScript on every page!

Just expecting that if I would save some kilobytes on my .html files by rendering my header and footer on each page via JavaScript?

CodePudding user response:

I agree that it will make life lot simpler, but in response to your query, utilise javascript as follows.

index.html


    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Document</title>
      <script type=module src="./index.js"></script>
    </head>
    
    <body>
      <my-header></my-header> 
      
      <h1>Home Page</h1>
      
      <my-footer></my-footer>
    </body>
     
    </html>

about.html


    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Document</title>
      <script type=module src="./index.js"></script>
    </head>
    
    <body>
      <my-header></my-header> 
      
      <h1>About Page</h1>
      
      <my-footer></my-footer>
    </body>
     
    </html>

contact.html


    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Document</title>
      <script type=module src="./index.js"></script>
    </head>
    
    <body>
      <my-header></my-header> 
      
      <h1>Contact Page</h1>
      
      <my-footer></my-footer>
    </body>
     
    </html>

index.js


    class MyHeader extends HTMLElement {
      connectedCallback() {
        this.innerHTML = `
        <header>
          <nav>
            <ul>
              <li><a href=index.html>Home</a></li>
              <li><a href=about.html>About</a></li>
              <li><a href=contact.html>Contact</a></li>
            </ul>
          </nav>
        </header>`;
      }
    }
    customElements.define("my-header", MyHeader);
    
    class MyFooter extends HTMLElement {
      connectedCallback() {
        this.innerHTML = `
        <footer>
          &copy; 2022 My Company
        </footer>`;
      }
    }
    customElements.define("my-footer", MyFooter);

Hope this helps you.

CodePudding user response:

I would seriously recommend using a frontend framework, such as Angular, Vue, Svelte, etc. You can create components for your headers and footers and then reused these across multiple places.

  • Related