3

I inject some JSON-LD into a page dynamically via Javascript, when I test the page using Google's Structured Data Testing Tool, the expected output appears and I can see the Product Element is rendered.

However, if I defer loading of the script that is responsible for fetching the JSON-LD content and then call the function to inject it in a window "load" event listener, the content no longer appears in the Structured Data Testing Tool.

In short the testing tool shows my markup when I do this...

<script src="https://example.site.com/rich-snippet/dist.js"></script>
<script>
    richSnippet();
</script>

But not when I do this.

<script src="https://example.site.com/rich-snippet/dist.js" defer=""></script>
<script>
    window.addEventListener('load', (event) => {
        richSnippet();
    });
</script>

I guess I'm asking whether this is a shortcoming in the Testing Tool or whether the defer / onload approach is a step too far in terms of Google being able to index the content.

2
  • Why would you add this markup via JavaScript at all? Seems like having it in the HTML code would be the most straightforward way and most likely to get picked up by search engines. Commented Sep 11, 2019 at 14:13
  • Because it is fetched via an API to include latest product review data (live total, aggregate rating and review content) this can't really be static HTML as would require updating more than hourly with latest data. Could fetch data server side on page load but that would require much more implementation and not be site agnostic. :)
    – Luke
    Commented Sep 11, 2019 at 14:20

2 Answers 2

4
<script src="https://example.site.com/rich-snippet/dist.js" defer=""></script>
<script>
    window.addEventListener('load', function() {
        richSnippet();
    });
</script>

Removing the ES6 syntax seems to resolve the issue, I think due the context of the event that would be passed.


Stephen Ostermiller:

Why would you add this markup via JavaScript at all? Seems like having it in the >HTML code would be the most straightforward way and most likely to get picked up by search engines.

Why would you not use JavaScript or any other language? Having the hardcoded HTML is counter intuitive in every case that comes to mind.

2

The Structured Data Testing Tool has very limited ability to deal with JavaScript.

However Googlebot and their other testing tools (URL Inspection, Rich Results Testing Tool, Mobile Friendly Tester) all render pages using a recent version of Chrome, so deal with JavaScript very well.

If the Rich Results Testing Tool does not directly report on the structured data you use, copy its rendered html into the SDTT.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.