首页 > 解决方案 > 使所有页面都可用

问题描述

我的网络应用程序在几个 html 页面之间路由。而不是唯一地定义每个文件的头,即键入:

  <head>
    <meta charset="utf-8">
    <link rel="stylesheet" type="text/css" href="/css/interface.css"></link>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script src="https://kit.fontawesome.com/6873aa3c17.js" crossorigin="anonymous"></script>
    ...
  </head>

每次,我可以在所有 HTML 文件中以编程方式加载所有这些脚本吗?(可以接受 JQuery 和 Vanilla)

我尝试的一种方法是创建一个include.js在每个头中加载的脚本,其中包含以下内容:

[
  'https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js',
  'https://kit.fontawesome.com/6873aa3c17.js'
].forEach(function(src) {
  var script = document.createElement('script');
  script.src = src;
  document.head.appendChild(script);
});

(并且可能是类似的链接解决方案)但这不起作用

提前致谢

标签: javascriptjqueryhtml

解决方案


如果您的网站是没有服务器端逻辑的静态 HTML 网站,我建议使用parcelwithposthtml-include

https://github.com/parcel-bundler/parcel

https://github.com/posthtml/posthtml-include

https://github.com/parcel-bundler/parcel/issues/915#issuecomment-369489539

您将能够包含这样的 html 文件:

<!doctype html>
<html>
<body>
    <include src="title.html"></include>
</body>
</html>

推荐阅读