top | item 45107190

(no title)

alserio | 6 months ago

I was wondering, are template elements a good place to store json data in the page to be consumed by js?

discuss

order

jfagnani|6 months ago

No. I would use <script type="-json">

<script> parses its contents as text, whereas <template> parses as DOM. This means you don't have to escape `<`, just `</script>`.

Myself and some browser engineers been working on proposals to allow for inline modules, including JSON, that are importable into other modules via regular import statements.

This is why I recommend the "-json" type - so it doesn't collide with a future native "json" type.

alserio|6 months ago

Thank you. And that proposal seems really interesting. Can I ask for a link if you happen to have one publicly accessible?

yuchi|6 months ago

As good as a script element with type application/json.

joeframbach|6 months ago

I wonder if the browser would attempt to validate the contents of a script tag with type json, versus treating it as a blob that would only be validated when parsed/used. And any performance overhead at load time for doing so. Not at a machine at the moment so I can't verify.

alserio|6 months ago

well one difference is that application/json scripts are still subject to CSP policies

Gualdrapo|6 months ago

For my portfolio (miler.codeberg.page) and the refactor&redesign I'm doing of it (that I hope to finish soon!), I feed some <template>s with data coming from a json that acts like kind of a database. I feel the process of querying nodes and setting their data is still a bit rudimentary in plain JS and it should be a pain in the ass for huge datasets or lots of nodes, but at least with modern JS it is not necessary to fetch the json with a XMLHTTPRequest or something - it can work importing it like a regular JS module, so at least there's that.