Set dynamic Meta Tags and Open Graph tags using jQuery

Viewed 12230

I'm trying to add dynamic tags using jQuery but it seems not to work. I load my script directly after loading the page.

This is my HTML

<!DOCTYPE html>
<html lang="en">
  <head>
    <script type="text/javascript" src="script.js"></script>
  </head>
  <body>
  </body>
</html>

This is how I add the tags on jQuery.

$(function() {
      $('head').append('<meta property="og:type" content="profile"/>'); 
      $('head').append('<meta property="og:url" content=""/>');
      $('head').append("<meta property='og:title' content="+text+"'/>");
      $('head').append("<meta property='og:image' content="+imageUrl+"'/>");
  });

Why I'm doing this? After the user is visiting the page example.com/?link=HDI635 I would like to present a small overview of the content. So I make a API call using jQuery after that I would like to add the values from the API response to the Open Graph tags.

3 Answers

As Alan stated, most web crawlers do not run JavaScript, they simply just download the HTML and read it as it is. As of today, FB crawler doesn't.

A good solution for this is having a server (nginx is enough) to detect the User Agent of the visitor and if it is Facebook's UA (https://developers.facebook.com/docs/sharing/webmasters/crawler/) serve a simple HTML with the OG tags. Else, serve the web-app.

You can update meta tags with JavaScript like that:

const title = "your title;
const description = "your description";
$('meta[name="description"]').attr('content', description);
$('meta[property="og:title"]').attr('content', title);
$('meta[property="og:description"]').attr('content', description);
// etc.

Google DOES read and run JavaScript stuff and it does at least read the meta-name-tags. See https://developers.google.com/search/docs/guides/javascript-seo-basics

Related