仅用HTML、CSS、JS能否实现网站模板复用与内容扩展?
只用HTML/CSS/JS实现模板复用的方法
当然可以不用框架,纯前端就能搞定模板复用,不用把重复代码复制到每个HTML文件里,给你几个实用的方案:
- 方案一:用JavaScript加载公共组件文件
把页面的公共部分(比如头部导航、底部版权栏)单独存成独立的HTML文件,比如header.html、footer.html,然后在每个业务页面里用JS把这些文件内容插入到指定位置。
举个例子:
- 先写公共的
header.html:
<header> <nav> <a href="/">首页</a> <a href="/about">关于我们</a> <a href="/contact">联系我们</a> </nav> </header>
- 业务页面(比如
index.html)里预留插入位置:
<body> <div id="header-container"></div> <!-- 这里是当前页面的专属内容 --> <main> <h1>首页欢迎你</h1> <p>这是首页的独特内容</p> </main> <div id="footer-container"></div> <script src="load-template.js"></script> </body>
- 写
load-template.js来加载公共组件:
// 等待DOM加载完成再执行 document.addEventListener('DOMContentLoaded', function() { // 加载头部 fetch('header.html') .then(res => res.text()) .then(html => { document.getElementById('header-container').innerHTML = html; }) .catch(err => console.error('加载头部失败:', err)); // 加载尾部 fetch('footer.html') .then(res => res.text()) .then(html => { document.getElementById('footer-container').innerHTML = html; }) .catch(err => console.error('加载尾部失败:', err)); });
这种方法简单直接,适合小型项目,缺点是首次加载会多几个HTTP请求,不过可以通过浏览器缓存缓解。
- 方案二:用HTML
<template>标签+JS
如果不想拆分多个文件,可以把公共模板写在一个单独的HTML文件里的<template>标签中,再用JS克隆模板内容插入到业务页面的指定位置。
比如:
<!-- 模板文件template.html --> <template id="header-template"> <header> <!-- 公共头部内容 --> </header> </template> <template id="footer-template"> <footer> <!-- 公共尾部内容 --> </footer> </template>
然后在业务页面里加载这个模板文件,再克隆插入:
fetch('template.html') .then(res => res.text()) .then(html => { // 创建临时DOM元素存放模板内容 const tempDiv = document.createElement('div'); tempDiv.innerHTML = html; // 克隆头部模板并插入 const headerTemplate = tempDiv.querySelector('#header-template'); const headerClone = document.importNode(headerTemplate.content, true); document.getElementById('header-container').appendChild(headerClone); // 克隆尾部模板并插入 const footerTemplate = tempDiv.querySelector('#footer-template'); const footerClone = document.importNode(footerTemplate.content, true); document.getElementById('footer-container').appendChild(footerClone); });
- 方案三:用服务器端包含(SSI)
如果你的服务器支持SSI(比如Apache、Nginx),可以直接在HTML里用SSI指令引入公共文件,不需要JS参与。比如:
<!-- Apache环境下使用 --> <!--#include virtual="/header.html" --> <!-- Nginx需配置后使用 --> <!--#include file="header.html" -->
这种方法是服务器在返回页面之前就把公共内容合并进去,前端看不到加载过程,体验更好,但需要服务器支持并做相应配置。
注意:如果用JS加载的方案,要考虑SEO问题——部分搜索引擎爬虫可能不会执行JS加载的内容,如果对SEO要求高,优先考虑SSI或者预编译类模板工具(比如Pug、Nunjucks),提前编译成静态HTML文件。
内容的提问来源于stack exchange,提问作者Komkry
相关产品推荐
相关产品推荐

