views:

121

answers:

2

What is the best way to include data in an HTML page? 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

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

  • Load the data via an XMLHttpRequest after the page has loaded

  • XML Data Islands

All of these methods seem to come with drawbacks so I would like to know what your thoughts are.

+3  A: 

I'd go with JSON. Or some other JavaScript code if there is reason for it. That will be easiest for the script to consume, and it is limited only to what the script itself is limited to.

Vilx-
I agree. It's also an order of magnitude faster than XML. Load your JSON via Ajax to keep it 'hidden'.
Diodeus
Yes, I like this way the best. I was worried that this would essentially be like putting the data in a global variable, but the more I think about it that is no different to any of the other methods. Thanks
foxy
+3  A: 

I would use JSON in a <script> element. 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.

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.

Loading the data through XHR after page load is fine, but it's not strictly an answer to the question. 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.

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

ddaa
Thanks. Making it an actual script would certainly be cleanest but in this case it would involve making two round-trips to the database for the same set of records (once to generate the html and once for the script file) when I could get away with one if I store the data in a script element.
foxy
I completely agree that putting the data in a separate script file is the best approach, but you know, that will incur an extra http round trip as well, where as putting the data directly in the page would not. Of course a separate file can be cached, but then so can an XHR call.
Benry
Not sure why you are all talking of script files. I am talking of an inline script.
ddaa