包括静态html文件中的头文件

时间:2018-03-15 11:44:28

标签: html

我想要一个单独的html文件,包括元数据,链接&脚本标记以及一个文件中的可见标题,然后我将其导入到我的静态html页面中。

所以我一直在尝试w3schools suggested solution,但这会在页面加载时导致令人不快的闪光。

基本上我的静态页面沿着这些行开始

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns="http://www.w3.org/1999/html">

function includeHTML() {
  var z, i, elmnt, file, xhttp;
  /*loop through a collection of all HTML elements:*/
  z = document.getElementsByTagName("*");
  for (i = 0; i < z.length; i++) {
    elmnt = z[i];
    /*search for elements with a certain atrribute:*/
    file = elmnt.getAttribute("include-html");
    if (file) {
      /*make an HTTP request using the attribute value as the file name:*/
      xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
        if (this.readyState == 4) {
          if (this.status == 200) {elmnt.innerHTML = this.responseText;}
          if (this.status == 404) {elmnt.innerHTML = "Page not found.";}
          /*remove the attribute, and call this function once more:*/
          elmnt.removeAttribute("include-html");
          includeHTML();
        }
      } 
      xhttp.open("GET", file, true);
      xhttp.send();
      /*exit the function:*/
      return;
    }
  }
}

</script>

<div include-html="staticheader.html"></div>

<body> 

然后包含html的主体并像这样完成

<div include-html="staticfooter.html"></div>

</body>

<script>
    includeHTML();
</script>

</html>

在staticheader.html中是元数据,css和js(包括bootstrap)的所有标签。也许这是不可能的,我假设它正在加载页面,到达底部并加载页眉和页脚然后应用导入。难怪在页面正确格式化之前有毫秒延迟!

我只有大约10个静态页面,所以通过将标题数据放回到单个html文件中来解决问题并不是世界末日,但我希望有更好的解决方案?

0 个答案:

没有答案