Adding JSON-LD with JavaScript

坚强是说给别人听的谎言 提交于 2021-01-27 05:27:26

问题


I am trying to implement structure data using JSON-LD. What I am doing is dynamically get content using jQuery and making JSON format and appending inside the head element.

<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));
});

Do both ways (creating the script element and storing the JSON-LD / storing the JSON-LD using ID) work? Which is the best implementation way? Also, does Google crawl dynamically added JSON-LD like above, using JavaScript?


回答1:


Yes, Google can crawl dynamically added JSON-LD, as explained in this Google article on the topic:

Google can read JSON-LD data when it is dynamically injected into the page's contents, such as by JavaScript code or embedded widgets in your content management system.

Both methods will definitely work, but if you're going to store the JSON-LD using ID you'll need to add the required type attribute to the script:

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

Once you finish adding your markup, make sure to test it with Google's Structured Data Testing Tool!




回答2:


I use

var Client = require("node-rest-client").Client;
var client = new Client();
var args = {
    headers: { "Accept": "application/ld+json, */*;q=0.5" }
 };

client.get(url+query,args, function (data, response) {
    ......
}


来源:https://stackoverflow.com/questions/51376310/adding-json-ld-with-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!