Include html in another html file

后端 未结 6 1317
无人及你
无人及你 2020-12-02 21:14

I have a html \"head\" template and a navigation template that I want to include in all my other html files for my site. I found this post:

Include another HTML fi

6条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-02 21:27

    For anyone interested in a Web Component approach:

    
    

    And the corresponding JS:

    class HTMLInclude extends HTMLElement {
      constructor() {
        super();
        this.innerHTML = "Loading...";
        this.loadContent();
      }
    
      async loadContent() {
        const source = this.getAttribute("src");
        if (!source) {
          throw new Error("No src attribute given.");
        }
        const response = await fetch(source);
        if (response.status !== 200) {
          throw new Error(`Could not load resource: ${source}`);
        }
        const content = await response.text();
        this.innerHTML = content;
      }
    }
    
    window.customElements.define("html-include", HTMLInclude);
    

    Note that it is possible to do some nice things with a shadow DOM to make sure styling of loaded content does not influence the outer page.

    The above code is pretty "modern" JS and you might not want to use the above code directly without some polyfills/babel transpilation.

提交回复
热议问题