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

What is the best way to include data in an HTML page? Data is not human readable and will be processed using a script after the page loads. Possible options:

  • Using class and title attributes in hidden / empty <div> or <span> elements on the page

  • JSON in the <script> element at the bottom of the page

  • Load data via XMLHttpRequest after page loading

  • XML data islands

All of these methods seem to have flaws, so I would like to know what your thoughts are.

+2
source share
2 answers

I would use JSON in the <script> element. In fact, I would make it an actual script. The browser will analyze and evaluate JSON, so take the opportunity to save it in some variable.

Hiding elements with CSS is pretty fragile, as some clients (not necessarily browsers thinking search engines) can still see them as part of the pageโ€™s data.

Downloading data via XHR after loading the page is fine, but this is not strictly the answer to the question. It is also a bit slower as it carries an extra server round (think about your antipodey users, low latency is very important for them).

XML data islands: I'm not sure what you're talking about, but it looks like it can cause a lot of complaints about the validator and can be fragile in that the node string can be displayed by the browser.

So, storing data in a <script> element sounds like the easiest, safest, and most appropriate way to answer a question.

+3
source

I would go with JSON. Or some other JavaScript code if there is a reason for this. This will be the easiest way to use the script, and is limited only to what is limited to the script.

+3
source

All Articles