In my last post, I described the importance of JSON-LD that will help you improve your website SEO. Now I will demonstrate some techniques of how to implement JSON-LD structure data with vanilla JavaScript as well as in popular frameworks.
We’ve seen how we can include a script tag with the JSON-LD data on the page. We can do that straight in the HTML of a page in the back end. With JavaScript, you can implement it dynamically on the client-side.
Pro tip:_ If you implement using server-side rendering, your website will be more SEO-Friendly._
Here is an example of a vanilla JavaScript implementation:
const jsonldScript = document.createElement('script');
jsonldScript.setAttribute('type', 'application/ld+json');
const structuredData = {
"@context": "https://schema.org/",
"@type": "Recipe",
"name": "Party Coffee Cake",
"author": {
"@type": "Person",
"name": "Mary Stone"
},
"datePublished": "2018-03-10",
"description": "This coffee cake is awesome and perfect for parties.",
"prepTime": "PT20M"
};
jsonldScript.textContent = structuredData;
document.head.appendChild(jsonldScript);
In this example, I’m creating a script element of type application/ld+json
and assigning the JSON-LD structured data to the textContent
property.
#javascript #json-ld #react #seo #vuejs #programming