February 2026

Embedding JSON in HTML <template> Tags

Head's up

Probably you shouldn't do this. Just put stuff in a script tag. But, still it's intersting to poke at.

Update

Got a great pointer from this response that points to using <script> tags as data blocks. Very cool.

Ok. Hear me out.

We embed pre-baked JSON in <template> tags.

Something like:

HTML

<template id="myStuff" data-type="json">
  {
    "items": ["alfa", "bravo", "charlie"]
  }
</template>

<template id="myThings" data-type="json">
  {
    "items": ["delta", "echo", "foxtrot"]
  }
</template>

<p>template tags don't output by default.</p>

Output

template tags don't output by default.

Doing Stuff and Things

Data can be pulled in by querying for data-type="json". Parsing values is done by running the .innerHTML through .toString().

Putting it all together, we get this:

JavaScript

const data = {};

function loadData() {
  document.querySelectorAll("[data-type=json]")
    .forEach((el) => {
      try {
        data[el.id] = 
          JSON.parse(el.innerHTML.toString());
      } catch(error) {
        console.error(error);
      }
    });
}

function renderData(query, key) {
  document.querySelector(query)
    .innerHTML = data[key].items.join(" - ");
}

loadData();
renderData(".stuff", "myStuff");
renderData(".things", "myThings");

HTML

<div class="stuff"></div>
<div class="things"></div>

Output

Less (Net)work

I like it this a lot. Perfect for times when I've got static JSON (e.g. configs for more functionality on the page). It feels nicer to embed than fetching it with a network call.

-a

end of line

Endnotes

Again, maybe probably don't do this. Just throw stuff into a script tag unless you've got a good reason not to.

This idea hit me while working on the next version of bitty. I was setting it up to pull in templates automatically. I realized we can do the same thing with data.

If you know of reasons this might go off the rails, please let me know.

See also this response which suggest using <script> tags as data blocks.

References

A bunch of functionality to support vanilla javascript development. All bundled in a single file.