在 DOM 中嵌入任意 JSON 的最佳实践? [英] Best practice for embedding arbitrary JSON in the DOM?

查看:21
本文介绍了在 DOM 中嵌入任意 JSON 的最佳实践?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在考虑像这样在 DOM 中嵌入任意 JSON:

I'm thinking about embedding arbitrary JSON in the DOM like this:

<script type="application/json" id="stuff">
    {
        "unicorns": "awesome",
        "abc": [1, 2, 3]
    }
</script>

这类似于在 DOM 中存储任意 HTML 模板以供以后与 JavaScript 模板引擎一起使用的方式.在这种情况下,我们稍后可以检索 JSON 并使用以下命令对其进行解析:

This is similar to the way one might store an arbitrary HTML template in the DOM for later use with a JavaScript template engine. In this case, we could later retrieve the JSON and parse it with:

var stuff = JSON.parse(document.getElementById('stuff').innerHTML);

这有效,但这是最好的方法吗?这是否违反了任何最佳实践或标准?

This works, but is it the best way? Does this violate any best practice or standard?

注意:我不是在寻找在 DOM 中存储 JSON 的替代方法,我已经确定这是我遇到的特定问题的最佳解决方案.我只是在寻找最好的方法.

推荐答案

我认为你原来的方法是最好的.HTML5 规范甚至解决了这种用途:

I think your original method is the best. The HTML5 spec even addresses this use:

"当用于包含数据块(相对于脚本)时,数据必须嵌入内联,数据格式必须使用type 属性,不得指定 src 属性,并且脚本元素的内容必须符合要求为使用的格式定义."

"When used to include data blocks (as opposed to scripts), the data must be embedded inline, the format of the data must be given using the type attribute, the src attribute must not be specified, and the contents of the script element must conform to the requirements defined for the format used."

在这里阅读:http://dev.w3.org/html5/spec/Overview.html#the-script-element

你已经做到了.什么叫不爱?不需要对属性数据进行字符编码.如果需要,您可以对其进行格式化.它具有表现力,预期用途很明确.感觉不像是一个黑客(例如,使用 CSS 来隐藏你的运营商"元素).这是完全有效的.

You've done exactly that. What is not to love? No character encoding as needed with attribute data. You can format it if you want. It's expressive and the intended use is clear. It doesn't feel like a hack (e.g. as using CSS to hide your "carrier" element does). It's perfectly valid.

这篇关于在 DOM 中嵌入任意 JSON 的最佳实践?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆