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?