简体   繁体   English

在HTML页面中包含数据的最佳方法是什么?

[英]What is the best way to include data in an HTML page?

What is the best way to include data in an HTML page? 在HTML页面中包含数据的最佳方法是什么? The data is not human-readable and will be processed by a script once the page has loaded. 该数据不是人类可读的,并且在页面加载后将由脚本进行处理。 The options I can think of are: 我能想到的选择是:

  • Using class and title attributes on hidden/empty <div> or <span> elements within the page 在页面中的隐藏/空<div><span>元素上使用class和title属性

  • JSON in a <script> element at the bottom of the page 页面底部<script>元素中的JSON

  • Load the data via an XMLHttpRequest after the page has loaded 页面加载后通过XMLHttpRequest加载数据

  • XML Data Islands XML数据岛

All of these methods seem to come with drawbacks so I would like to know what your thoughts are. 所有这些方法似乎都有缺点,所以我想知道您的想法。

I'd go with JSON. 我会使用JSON。 Or some other JavaScript code if there is reason for it. 或其他一些JavaScript代码(如果有原因的话)。 That will be easiest for the script to consume, and it is limited only to what the script itself is limited to. 这对于脚本来说是最容易使用的,并且仅受脚本本身所限制的限制。

I would use JSON in a <script> element. 我会在<script>元素中使用JSON。 Actually, I would make it an actual script. 实际上,我会将其设为实际脚本。 The browser is going to parse and evaluate the JSON, so take the opportunity to store it in some variable. 浏览器将解析和评估JSON,因此请抓住机会将其存储在某些变量中。

Hiding elements using CSS is kind of fragile, as some clients (not necessarily browsers, think search engines) may still see them as part of the page data. 使用CSS隐藏元素有点脆弱,因为某些客户端(不一定是浏览器,认为搜索引擎)可能仍将它们视为页面数据的一部分。

Loading the data through XHR after page load is fine, but it's not strictly an answer to the question. 在页面加载之后通过XHR加载数据是可以的,但是严格来说,这并不是问题的答案。 Its also a bit slower as it incurs an additional server round-trip (think of your antipodean users, low latency is very important to them). 它也要慢一些,因为它会导致服务器往返。(想想对立的用户,低延迟对他们来说非常重要)。

XML Data Islands: I am not sure what you are referring to, but it sound like something that would cause much validator complaints, and which might be fragile in that string node could be rendered by the browser. XML数据岛:我不确定您要指的是什么,但听起来可能会引起验证者的抱怨,并且在该字符串节点中可能是脆弱的,浏览器可能会呈现出来。

So, storing the data in a <script> element sounds like the simplest, safest, most appropriate way to answer the question. 因此,将数据存储在<script>元素中似乎是回答问题的最简单,最安全,最适当的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM