使用JavaScript添加JSON-LD

问题描述 投票:1回答:1

我正在尝试使用JSON-LD实现结构数据。我正在做的是使用jQuery动态获取内容并制作JSON格式并附加到head元素中。

<script id="dynamicJSONLD"></script>
$(document).ready(function(){
var product_name = $(.product-pg .product-name).text();
data = {
               "@context": "https://schema.org",
               "@type": "Product",
               "url": "https://www.example.com/productone",
               "name": product_name  
            };

//creating the script element and storing the JSON-LD

var script = document.createElement('script');
script.type = "application/ld+json";
script.innerHTML = JSON.stringify(data);
document.getElementsByTagName('head')[0].appendChild(script);

//OR

//storing the JSON-LD using ID
$("#dynamicJSONLD").html(JSON.stringify(data));
});

两种方式(创建script元素和存储JSON-LD /使用ID存储JSON-LD)都有效吗?哪种方式最好?此外,Google是否使用JavaScript抓取动态添加的JSON-LD,如上所述?

javascript json-ld
1个回答
1
投票

是的,Google可以抓取动态添加的JSON-LD,如this Google article中有关该主题的解释:

当Google动态注入页面内容时,Google可以读取JSON-LD数据,例如内容管理系统中的JavaScript代码或嵌入式小部件。

这两种方法肯定都有用,但是如果你要使用ID存储JSON-LD,你需要在脚本中添加所需的type属性:

<script id="dynamicJSONLD" type="application/ld+json"></script>

添加完标记后,请务必使用Google's Structured Data Testing Tool进行测试!

© www.soinside.com 2019 - 2024. All rights reserved.