I set dynamic schema for breadcrumb in JavaScript code ,and very thing is ok. but when tested Url in the rich result test from google ,often time does not find schema for this. when I see inspect of my page, schema existed of the script tag.
what is reason that don't working well.?
JavaScript code is this:
<script>
var bread = {
"@@context": "https://www.schema.org",
"@@type": "BreadcrumbList",
"itemListElement": []
}
var exist = false;
$('.breadcrumb li').each(function (index) {
var item = {}
var href = $(this).find("a").attr('href');
if (href) item["@@id"] = "@Repository.Settings["WebSiteAddress"]" + href // OR location.protocol+"//"+location.host+href;
else item["@@id"] = "@Repository.Settings["WebSiteAddress"]" + window.location.pathname
item["name"] = $.trim($(this).text());
bread.itemListElement.push({
"@@type": "ListItem",
"position": index + 1,
item
})
exist = true;
});
if(exist){
var jsonStrb = JSON.stringify(bread);
var s2 = document.createElement("script");
s2.type = "application/ld+json";
s2.id = "BreadcrumbJson";
$("body").append(s2);
$('#BreadcrumbJson').append(jsonStrb);
} </script>
It could be because the code runs before the DOM is ready, so the RRT doesn't pick it up.
Try running it afterwards - as you're using jQuery - by wrapping your code in the .ready method:
$(document).ready(function() {
// your code
});
Also, make sure you're using a valid JSON-LD syntax. Namely, special properties should have a single "@" character (e.g. "@context", "@type"), instead of double ("@@context", "@@type" and so on), although the code looks fine on your screenshot/localhost, unlike the separate code snippet you've provided.