
在现代 web 开发中,许多页面的内容并非静态不变,而是依赖于用户交互、api 调用或实时数据。例如,一个电商产品的评分、库存或价格可能会频繁变动。为了确保搜索引擎(如 google)能够准确抓取并理解这些动态更新的数据,并将其展示为富媒体搜索结果(rich results),我们需要一种机制来动态生成和更新页面的 json-ld 结构化数据。手动修改 html 中的静态 json-ld 脚本显然不切实际,因此,利用 javascript 在客户端进行动态生成和注入成为了一种高效且灵活的解决方案。
动态更新 JSON-LD 的最直接有效的方法是,在页面加载后,利用 JavaScript 完全构建或重新构建包含结构化数据的 <script type="application/ld+json"> 标签,并将其注入到文档的 <head> 部分。这种方法允许我们根据任何可用的动态数据来填充 Schema 属性。
以下是实现这一过程的详细步骤和示例代码。
首先,我们需要获取或定义那些将用于填充 JSON-LD 属性的动态数据。这些数据可能来自 API 响应、用户输入或页面上已有的 DOM 元素。
const productData = {
"name": "动态产品名称",
"ratingValue": "4.9", // 动态评分值
"ratingCount": "77", // 动态评分数量
"lowPrice": "5.76",
"highPrice": "8",
"availability": "http://schema.org/InStock", // 动态库存状态
"priceCurrency": "USD"
};接下来,根据 Schema.org 的规范,使用准备好的动态数据构建一个 JavaScript 对象,该对象将代表我们的 JSON-LD 结构。
立即学习“Java免费学习笔记(深入)”;
const structuredData = {
"@context": "http://schema.org/",
"@type": "Product",
"name": productData.name, // 使用动态产品名称
"aggregateRating": {
"@type": "AggregateRating",
"ratingValue": productData.ratingValue, // 动态评分值
"ratingCount": productData.ratingCount // 动态评分数量
},
"offers": {
"@type": "AggregateOffer",
"lowPrice": productData.lowPrice,
"highPrice": productData.highPrice,
"availability": productData.availability,
"priceCurrency": productData.priceCurrency
}
};在这个例子中,我们针对一个 Product 类型,动态设置了 aggregateRating 中的 ratingValue 和 ratingCount,以及 offers 中的价格和库存信息。
最后一步是利用 DOM API 创建一个新的 <script> 元素,设置其 type 属性为 application/ld+json,将之前构建的 structuredData 对象转换为 JSON 字符串作为其 textContent,然后将其附加到文档的 <head> 元素中。
// 创建一个新的 script 元素
const scriptElement = document.createElement('script');
// 设置 script 元素的 type 属性
scriptElement.setAttribute('type', 'application/ld+json');
// 将结构化数据对象转换为 JSON 字符串并赋值给 script 元素的 textContent
scriptElement.textContent = JSON.stringify(structuredData);
// 将 script 元素附加到文档的 <head> 部分
document.head.appendChild(scriptElement);
// 可选:为了验证,可以将生成的 JSON 显示在页面某个位置
// const showDiv = document.getElementById('show');
// if (showDiv) {
// showDiv.innerHTML = `<pre>${JSON.stringify(structuredData, null, 2)}</pre>`;
// }完整的 JavaScript 代码示例:
// 1. 准备动态数据
const productData = {
"name": "我的神奇产品", // 示例动态数据
"ratingValue": "4.9",
"ratingCount": "77",
"lowPrice": "5.76",
"highPrice": "8",
"availability": "http://schema.org/InStock",
"priceCurrency": "USD"
};
// 2. 构建 JSON-LD 结构化数据对象
const structuredData = {
"@context": "http://schema.org/",
"@type": "Product",
"name": productData.name,
"aggregateRating": {
"@type": "AggregateRating",
"ratingValue": productData.ratingValue,
"ratingCount": productData.ratingCount
},
"offers": {
"@type": "AggregateOffer",
"lowPrice": productData.lowPrice,
"highPrice": productData.highPrice,
"availability": productData.availability,
"priceCurrency": productData.priceCurrency
}
};
// 3. 创建并注入 <script> 标签
function injectStructuredData() {
// 检查是否已存在旧的 JSON-LD script,如果需要更新则移除
const existingScript = document.querySelector('script[type="application/ld+json"]');
if (existingScript) {
existingScript.remove();
}
const scriptElement = document.createElement('script');
scriptElement.setAttribute('type', 'application/ld+json');
scriptElement.textContent = JSON.stringify(structuredData);
document.head.appendChild(scriptElement);
console.log("JSON-LD Script Injected:", structuredData); // 调试输出
}
// 在页面加载完成后执行注入
document.addEventListener('DOMContentLoaded', injectStructuredData);
// 如果需要动态更新,可以再次调用 injectStructuredData()
// 例如:当产品评分数据更新时
// setTimeout(() => {
// productData.ratingValue = "4.5";
// productData.ratingCount = "80";
// structuredData.aggregateRating.ratingValue = productData.ratingValue;
// structuredData.aggregateRating.ratingCount = productData.ratingCount;
// injectStructuredData();
// console.log("JSON-LD Script Updated:", structuredData);
// }, 5000); // 5秒后模拟更新基本的 HTML 结构:
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>动态 JSON-LD 示例</title>
<!-- 建议将 JavaScript 代码放在 <body> 结束标签前,或在 DOMContentLoaded 事件中执行 -->
</head>
<body>
<h1>产品详情页</h1>
<p>这里是产品的其他内容...</p>
<div id="show"></div> <!-- 可选:用于显示生成的 JSON-LD 内容 -->
<script>
// 将上述 JavaScript 代码粘贴到这里,或者引入一个外部 JS 文件
// 1. 准备动态数据
const productData = {
"name": "我的神奇产品",
"ratingValue": "4.9",
"ratingCount": "77",
"lowPrice": "5.76",
"highPrice": "8",
"availability": "http://schema.org/InStock",
"priceCurrency": "USD"
};
// 2. 构建 JSON-LD 结构化数据对象
const structuredData = {
"@context": "http://schema.org/",
"@type": "Product",
"name": productData.name,
"aggregateRating": {
"@type": "AggregateRating",
"ratingValue": productData.ratingValue,
"ratingCount": productData.ratingCount
},
"offers": {
"@type": "AggregateOffer",
"lowPrice": productData.lowPrice,
"highPrice": productData.highPrice,
"availability": productData.availability,
"priceCurrency": productData.priceCurrency
}
};
// 3. 创建并注入 <script> 标签
function injectStructuredData() {
// 检查是否已存在旧的 JSON-LD script,如果需要更新则移除
const existingScript = document.querySelector('script[type="application/ld+json"]');
if (existingScript) {
existingScript.remove();
}
const scriptElement = document.createElement('script');
scriptElement.setAttribute('type', 'application/ld+json');
scriptElement.textContent = JSON.stringify(structuredData);
document.head.appendChild(scriptElement);
// 可选:在页面上显示生成的 JSON
const showDiv = document.getElementById('show');
if (showDiv) {
showDiv.innerHTML = `<h2>生成的 JSON-LD:</h2><pre>${JSON.stringify(structuredData, null, 2)}</pre>`;
}
}
// 确保 DOM 完全加载后再执行
document.addEventListener('DOMContentLoaded', injectStructuredData);
</script>
</body>
</html>以上就是JavaScript 动态生成与更新 JSON-LD Schema 脚本教程的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号