user254153
user254153

Reputation: 1883

Adding JSON-LD with JavaScript

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?

Upvotes: 5

Views: 9538

Answers (2)

Noah Jeffrey
Noah Jeffrey

Reputation: 119

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!

Upvotes: 7

Alvaro
Alvaro

Reputation: 651

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) {
    ......
}

Upvotes: 0

Related Questions