面试题答案
一键面试减少解析开销
- 缓存已解析模板:在实际项目中,比如开发一个单页应用(SPA),对于一些经常复用的模板,像用户列表项的模板。可以在首次解析模板后,将解析结果缓存起来。在后续需要使用该模板时,直接从缓存中获取,避免重复解析。例如使用一个简单的对象作为缓存容器:
const templateCache = {};
function getTemplate(templateStr) {
if (!templateCache[templateStr]) {
const template = document.createElement('template');
template.innerHTML = templateStr;
templateCache[templateStr] = template;
}
return templateCache[templateStr];
}
- 使用预编译:如果项目允许,可以采用预编译模板的方式。例如在使用Handlebars.js模板引擎时,可以在构建阶段将模板文件编译成JavaScript函数。这样在运行时,直接执行这些预编译好的函数,而无需在浏览器端进行解析。像在一个Node.js服务器渲染项目中,使用
handlebars - precompiler
工具,在构建过程中对模板进行预编译,极大提升了模板渲染速度。
提高复用性
- 模块化模板:将模板按照功能拆分成不同的模块。在开发电商项目时,商品展示模块、购物车模块都可以有各自独立的模板。通过导入这些模板模块,可以在不同的页面或组件中复用。例如在ES6模块系统中,将商品展示模板定义在
product - template.js
文件中:
// product - template.js
export const productTemplate = (product) => `
<div class="product">
<img src="${product.imageUrl}" alt="${product.name}">
<h3>${product.name}</h3>
<p>${product.price}</p>
</div>
`;
然后在其他组件中导入使用:
import { productTemplate } from './product - template.js';
// 使用模板渲染商品
const product = { imageUrl: 'image.jpg', name: 'Sample Product', price: '100' };
const productElement = document.createElement('div');
productElement.innerHTML = productTemplate(product);
- 参数化模板:使模板能够接受不同的参数来呈现不同的内容。在开发通用的弹窗组件模板时,通过传入不同的标题、内容和按钮文本等参数,实现多种类型弹窗的复用。例如:
function popupTemplate(title, content, buttonText) {
return `
<div class="popup">
<h2>${title}</h2>
<p>${content}</p>
<button>${buttonText}</button>
</div>
`;
}
// 创建不同的弹窗
const infoPopup = popupTemplate('Info', 'This is some information', 'Close');
const warningPopup = popupTemplate('Warning', 'Something is wrong', 'OK');
处理复杂逻辑的最佳实践
- 逻辑外置:避免在模板中嵌入过多复杂逻辑。当处理订单计算逻辑时,在模板中简单调用一个函数来获取计算结果。例如在Mustache模板中:
{{#order}}
<p>Total Price: {{calculateTotalPrice}}</p>
{{/order}}
在JavaScript代码中定义calculateTotalPrice
函数:
function calculateTotalPrice(order) {
let total = 0;
order.items.forEach(item => {
total += item.price * item.quantity;
});
return total;
}
- 使用辅助函数:对于一些常见的复杂逻辑,如日期格式化、字符串截断等,可以创建辅助函数。在一个博客项目中,对于文章发布日期的格式化,定义一个辅助函数:
function formatDate(date) {
return new Intl.DateTimeFormat('en - US', { year: 'numeric', month: 'long', day: 'numeric' }).format(date);
}
在模板中使用:
const post = { title: 'New Post', date: new Date() };
const postTemplate = `
<h1>${post.title}</h1>
<p>Published on ${formatDate(post.date)}</p>
`;