如何使用jQuery从现有脚本动态生成可在源代码中可见的JSON-LD脚本
实现方案说明
核心前置说明
- 所有通过客户端JS(包括jQuery)在页面加载完成后动态插入的
<script>标签,都不会出现在「查看源代码」的原始内容里:查看源代码展示的是服务端返回的未经过客户端修改的初始HTML内容,动态修改的内容只能在F12开发者工具的元素面板中看到。 - 目前Google爬虫已经支持解析客户端执行JS后生成的动态内容,只要你插入的JSON-LD格式正确,哪怕查看源代码里看不到,Google也可以正常识别。如果你必须要让内容出现在查看源代码里,只能通过服务端渲染/静态页面构建阶段把JSON-LD写入HTML,无法纯靠前端jQuery实现。
方案1:前端动态生成(Google可正常识别,满足绝大多数SEO需求)
步骤1:通过jQuery循环拿到目标数据
举个遍历商品列表的示例,可替换为你自己的业务逻辑:
// 存储遍历得到的结构化数据 const structuredData = [] $('.your-item-selector').each(function() { structuredData.push({ title: $(this).find('.title').text().trim(), price: $(this).find('.price').text().trim(), link: $(this).find('a').attr('href') // 其他需要的字段自行补充 }) })
步骤2:构造符合schema规范的JSON-LD结构
根据你要标记的内容类型替换对应结构,以下是商品列表的示例:
const jsonLdObj = { "@context": "https://schema.org", "@type": "ItemList", "itemListElement": structuredData.map((item, index) => ({ "@type": "ListItem", "position": index + 1, "item": { "@type": "Product", "name": item.title, "price": item.price, "url": item.link } })) }
步骤3:生成JSON-LD标签插入到页面
// 创建script标签 const ldScript = document.createElement('script') // 指定JSON-LD的类型 ldScript.type = 'application/ld+json' // 把JSON对象转为字符串写入标签 ldScript.textContent = JSON.stringify(jsonLdObj) // 插入到head末尾 document.head.appendChild(ldScript)
方案2:实现查看源代码可见(需要服务端配合)
如果必须要让JSON-LD出现在查看源代码中,需要提前把数据传给服务端,在服务端渲染页面的时候直接把JSON-LD拼到HTML的head部分,以下是PHP服务端的示例:
<?php // 服务端提前获取你需要的结构化数据,可由前端传参或者后端直接查询得到 $itemList = [ ['title' => '测试商品1', 'price' => '99元', 'link' => '/item/1'], ['title' => '测试商品2', 'price' => '199元', 'link' => '/item/2'] ]; // 构造JSON-LD结构 $jsonLd = [ "@context" => "https://schema.org", "@type" => "ItemList", "itemListElement" => array_map(function($item, $idx) { return [ "@type" => "ListItem", "position" => $idx +1, "item" => [ "@type" => "Product", "name" => $item['title'], "price" => $item['price'], "url" => $item['link'] ] ]; }, $itemList, array_keys($itemList)) ]; ?> <!-- 直接在head中输出JSON-LD,会出现在查看源代码中 --> <head> <script type="application/ld+json"> <?= json_encode($jsonLd, JSON_UNESCAPED_UNICODE) ?> </script> </head>
内容的提问来源于stack exchange,提问作者Sanaullah Channa
相关产品推荐
相关产品推荐

