我有几个 .html
文件,我希望所有这些文件都有相同的 header 。截至目前,我可以通过使用 html 导入在 Chrome 上执行此操作:
我有一个名为 CommonHead.html
的页面,其中包含一些 JS 和 CSS 文件,例如:
<!-- CommonHead.html -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
然后我有一堆其他 html 页面,我将其放在标题上:
<head>
<link rel="import" href="CommonHead.html">
</head>
效果很好。然而,Firefox 不支持这一点,所以我想要一种使用 JavaScript 来做同样事情的方法。我尝试了 .load
,使用 .ge
t 到变量中,将内容附加到标题等。似乎没有什么可以可靠地工作。
有谁知道使用 javascript/jquery 执行此操作的正确方法是什么?
最佳答案
Firefox 目前对 HTML 导入的立场可以在 here 找到。 :
As previously stated, Mozilla is not currently intending to implementing HTML Imports. This is in part because we’d like to see how ES6 modules pan out before shipping another way of importing external assets, and partly because we don’t feel they enable much that isn’t already possible.
We’ve been working with Web Components in Firefox OS for over a year and have found using existing module syntax (AMD or Common JS) to resolve a dependency tree, registering elements, loaded using a normal tag seems to be enough to get stuff done.
HTML Imports do lend themselves well to a simpler/more declarative workflow, such as the older and Polymer’s current registration syntax.
With this simplicity has come criticism from the community that Imports don’t offer enough control to be taken seriously as a dependency management solution.
理想情况下,您应该使用某种类型的服务器端代码(例如 PHP)来包含依赖项,并将它们输出到您正在呈现的每个 HTML 页面上。
示例index.php:
<html>
<head>
<title>Testing</title>
<?php include('includes/header.php'); ?>
</head>
</html>
或者,您也可以查看 HTML Imports polyfill,可以在 here 中找到它。 。这将允许您在 IE11+、Firefox、Chrome、Safari 7+ 和移动设备上使用 HTML 导入。请注意,不支持的设备(如 ie 10 及更低版本,将无法从此受益)。我强烈建议使用服务器端语言,以避免与旧客户端兼容。
其他一些可能性:
关于javascript - 模拟 head HTML 导入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40243703/