JavaScript 动态生成与更新 JSON-LD Schema 脚本教程

JavaScript 动态生成与更新 JSON-LD Schema 脚本教程

本教程详细介绍了如何使用 JavaScript 动态生成和更新 JSON-LD 结构化数据脚本。通过创建 <script> 标签并将其内容设置为动态构建的 JSON 对象,然后将其附加到文档头部,可以实现 Schema 标记的灵活管理,特别适用于需要根据用户行为或后端数据实时更新内容的场景,确保搜索引擎能够准确理解页面信息。<h3>动态生成 JSON-LD Schema 的必要性<p>在现代 web 开发中,许多页面的内容并非静态不变,而是依赖于用户交互、api 调用或实时数据。例如,一个电商产品的评分、库存或价格可能会频繁变动。为了确保搜索引擎(如 google)能够准确抓取并理解这些动态更新的数据,并将其展示为富媒体搜索结果(rich results),我们需要一种机制来动态生成和更新页面的 json-ld 结构化数据。手动修改 html 中的静态 json-ld 脚本显然不切实际,因此,利用 javascript 在客户端进行动态生成和注入成为了一种高效且灵活的解决方案。<h3>核心方法:JavaScript 构建并注入 Script 标签<p>动态更新 JSON-LD 的最直接有效的方法是,在页面加载后,利用 JavaScript 完全构建或重新构建包含结构化数据的 <script type="application/ld+json"> 标签,并将其注入到文档的 <head> 部分。这种方法允许我们根据任何可用的动态数据来填充 Schema 属性。<p>以下是实现这一过程的详细步骤和示例代码。<h4>1. 准备动态数据<p>首先,我们需要获取或定义那些将用于填充 JSON-LD 属性的动态数据。这些数据可能来自 API 响应、用户输入或页面上已有的 DOM 元素。<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">const productData = {
&quot;name&quot;: &quot;动态产品名称&quot;,
&quot;ratingValue&quot;: &quot;4.9&quot;, // 动态评分值
&quot;ratingCount&quot;: &quot;77&quot;, // 动态评分数量
&quot;lowPrice&quot;: &quot;5.76&quot;,
&quot;highPrice&quot;: &quot;8&quot;,
&quot;availability&quot;: &quot;http://schema.org/InStock&quot;, // 动态库存状态
&quot;priceCurrency&quot;: &quot;USD&quot;
};</pre><div class="contentsignin">登录后复制</div></div><h4>2. 构建 JSON-LD 结构化数据对象<p>接下来,根据 Schema.org 的规范,使用准备好的动态数据构建一个 JavaScript 对象,该对象将代表我们的 JSON-LD 结构。<p><span>立即学习“<a href="https://pan.quark.cn/s/c1c2c2ed740f" style="text-decoration: underline !important; color: blue; font-weight: bolder;" rel="nofollow" target="_blank">Java免费学习笔记(深入)”;<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">const structuredData = {
&quot;@context&quot;: &quot;http://schema.org/&quot;,
&quot;@type&quot;: &quot;Product&quot;,
&quot;name&quot;: productData.name, // 使用动态产品名称

&quot;aggregateRating&quot;: {
&quot;@type&quot;: &quot;AggregateRating&quot;,
&quot;ratingValue&quot;: productData.ratingValue, // 动态评分值
&quot;ratingCount&quot;: productData.ratingCount // 动态评分数量
},
&quot;offers&quot;: {
&quot;@type&quot;: &quot;AggregateOffer&quot;,
&quot;lowPrice&quot;: productData.lowPrice,
&quot;highPrice&quot;: productData.highPrice,
&quot;availability&quot;: productData.availability,
&quot;priceCurrency&quot;: productData.priceCurrency
}
};</pre><div class="contentsignin">登录后复制</div></div><p>在这个例子中,我们针对一个 Product 类型,动态设置了 aggregateRating 中的 ratingValue 和 ratingCount,以及 offers 中的价格和库存信息。<h4>3. 创建并注入 <script> 标签<p>最后一步是利用 DOM API 创建一个新的 <script> 元素,设置其 type 属性为 application/ld+json,将之前构建的 structu<a style="color:#f60; text-decoration:underline;" title= "red"href="https://www.php.cn/zt/122037.html" target="_blank">redData 对象转换为 JSON 字符串作为其 textContent,然后将其附加到文档的 <head> 元素中。<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">// 创建一个新的 script 元素
const scriptElement = document.createElement(‘script’);

// 设置 script 元素的 type 属性
scriptElement.setAttribute(‘type’, ‘application/ld+json’);

// 将结构化数据对象转换为 JSON 字符串并赋值给 script 元素的 textContent
scriptElement.textContent = JSON.stringify(structuredData);

// 将 script 元素附加到文档的 &lt;head&gt; 部分
document.head.appendChild(scriptElement);

// 可选:为了验证,可以将生成的 JSON 显示在页面某个位置
// const showDiv = document.getElementById(‘show’);
// if (showDiv) {
// showDiv.innerHTML = `&lt;pre class=&quot;brush:php;toolbar:false&quot;&gt;${JSON.stringify(structuredData, null, 2)}</pre><div class="contentsignin">登录后复制</div></div>`;
// }<p><strong>完整的 JavaScript 代码示例:<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">// 1. 准备动态数据
const productData = {
&quot;name&quot;: &quot;我的神奇产品&quot;, // 示例动态数据
&quot;ratingValue&quot;: &quot;4.9&quot;,
&quot;ratingCount&quot;: &quot;77&quot;,
&quot;lowPrice&quot;: &quot;5.76&quot;,
&quot;highPrice&quot;: &quot;8&quot;,
&quot;availability&quot;: &quot;http://schema.org/InStock&quot;,
&quot;priceCurrency&quot;: &quot;USD&quot;
};

// 2. 构建 JSON-LD 结构化数据对象
const structuredData = {
&quot;@context&quot;: &quot;http://schema.org/&quot;,
&quot;@type&quot;: &quot;Product&quot;,
&quot;name&quot;: productData.name,
&quot;aggregateRating&quot;: {
&quot;@type&quot;: &quot;AggregateRating&quot;,
&quot;ratingValue&quot;: productData.ratingValue,
&quot;ratingCount&quot;: productData.ratingCount
},
&quot;offers&quot;: {
&quot;@type&quot;: &quot;AggregateOffer&quot;,
&quot;lowPrice&quot;: productData.lowPrice,
&quot;highPrice&quot;: productData.highPrice,
&quot;availability&quot;: productData.availability,
&quot;priceCurrency&quot;: productData.priceCurrency
}
};

// 3. 创建并注入 &lt;script&gt; 标签
function injectStructuredData() {
// 检查是否已存在旧的 JSON-LD script,如果需要更新则移除
const existingScript = document.querySelector(‘script[type=&quot;application/ld+json&quot;]’);
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(&quot;JSON-LD Script Injected:&quot;, structuredData); // 调试输出
}

// 在页面加载完成后执行注入
document.addEventListener(‘DOMContentLoaded’, injectStructuredData);

// 如果需要动态更新,可以再次调用 injectStructuredData()
// 例如:当产品评分数据更新时
// setTimeout(() =&gt; {
// productData.ratingValue = &quot;4.5&quot;;
// productData.ratingCount = &quot;80&quot;;
// structuredData.aggregateRating.ratingValue = productData.ratingValue;
// structuredData.aggregateRating.ratingCount = productData.ratingCount;
// injectStructuredData();
// console.log(&quot;JSON-LD Script Updated:&quot;, structuredData);
// }, 5000); // 5秒后模拟更新</pre><div class="contentsignin">登录后复制</div></div><p><strong>基本的 HTML 结构:<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">&lt;!doctype html&gt;
&lt;html lang=&quot;zh-CN&quot;&gt;
&lt;head&gt;
&lt;meta charset=&quot;UTF-8&quot;&gt;
&lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;
&lt;title&gt;动态 JSON-LD 示例&lt;/title&gt;
&lt;!– 建议将 JavaScript 代码放在 &lt;body&gt; 结束标签前,或在 DOMContentLoaded 事件中执行 –&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;h1&gt;产品详情页&lt;/h1&gt;
&lt;p&gt;这里是产品的其他内容…&lt;/p&gt;
&lt;div id=&quot;show&quot;&gt;&lt;/div&gt; &lt;!– 可选:用于显示生成的 JSON-LD 内容 –&gt;

&lt;script&gt;
// 将上述 JavaScript 代码粘贴到这里,或者引入一个外部 JS 文件
// 1. 准备动态数据
const productData = {
&quot;name&quot;: &quot;我的神奇产品&quot;,
&quot;ratingValue&quot;: &quot;4.9&quot;,
&quot;ratingCount&quot;: &quot;77&quot;,
&quot;lowPrice&quot;: &quot;5.76&quot;,
&quot;highPrice&quot;: &quot;8&quot;,
&quot;availability&quot;: &quot;http://schema.org/InStock&quot;,
&quot;priceCurrency&quot;: &quot;USD&quot;
};

// 2. 构建 JSON-LD 结构化数据对象
const structuredData = {
&quot;@context&quot;: &quot;http://schema.org/&quot;,
&quot;@type&quot;: &quot;Product&quot;,
&quot;name&quot;: productData.name,
&quot;aggregateRating&quot;: {
&quot;@type&quot;: &quot;AggregateRating&quot;,
&quot;ratingValue&quot;: productData.ratingValue,
&quot;ratingCount&quot;: productData.ratingCount
},
&quot;offers&quot;: {
&quot;@type&quot;: &quot;AggregateOffer&quot;,
&quot;lowPrice&quot;: productData.lowPrice,
&quot;highPrice&quot;: productData.highPrice,
&quot;availability&quot;: productData.availability,
&quot;priceCurrency&quot;: productData.priceCurrency
}
};

// 3. 创建并注入 &lt;script&gt; 标签
function injectStructuredData() {
// 检查是否已存在旧的 JSON-LD script,如果需要更新则移除
const existingScript = document.querySelector(‘script[type=&quot;application/ld+json&quot;]’);
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 = `&lt;h2&gt;生成的 JSON-LD:&lt;/h2&gt;&lt;pre class=&quot;brush:php;toolbar:false&quot;&gt;${JSON.stringify(structuredData, null, 2)}</pre><div class="contentsignin">登录后复制</div></div>`;
}
}

// 确保 DOM 完全加载后再执行
document.addEventListener(‘DOMContentLoaded’, injectStructuredData);
</script>

以上就是JavaScript 动态生成与更新 JSON-LD Schema 脚本教程的详细内容,更多请关注php中文网其它相关文章!

https://www.php.cn/faq/1430172.html

发表回复

Your email address will not be published. Required fields are marked *