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.