Search code examples
javascripthtml

Is it a bad idea to use the meta tag in HTML to specify custom metadata for retrieval with JavaScript?


Whereas the following code works, I question whether or not it is bad practise to use it? I could achieve the same with a div inside the body. However, seeing as I am trying to get metadata from my html, it would seem logical to use the meta-tag. Is this okay, or can it have unexpected issues?

My use case is when information is passed down from the server through EJS and I don't want to have to make a redundant second request to my server from my JS to get the data that is already passed down when rendering the HTML.

const user = document.getElementById("meta_user");
console.log(user.getAttribute("data-content"));
<head>
  <meta data-name="user" data-content="{ name: 'test' }" id="meta_user">
</head>
<body>

</body>


Solution

  • From the specification:

    Exactly one of the name, http-equiv, charset, and itemprop attributes must be specified.

    If either name, http-equiv, or itemprop is specified, then the content attribute must also be specified. Otherwise, it must be omitted.

    Your use is missing all of these attributes. You should come up with a name attribute that describes this use, and make sure it doesn't conflict with any of the standard names, and preferably none of the names on the MetaExtensions wiki (you could also search there to see if something similar is already registered).