Reputation: 2168
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.
Upvotes: 2
Views: 1220
Reputation: 54544
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.
Upvotes: 4
Reputation: 107072
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.
Upvotes: 3