Example of <script type="text/csv">

Brian Campbell

This is inspired by Tab Atkin's <csv> proposal (and in fact is a slightly modified version of his code). I don't believe that a new element containing a completely different format with new parsing rules feels like it fits very well into HTML; you might as well start adding a <TeX> element instead of MathML, or a <pdf> instead of SVG.

There are already several ways of embedding other forms of content in HTML5. Among the options are simply including it in <pre>, possibly with a <code class="language-csv"> inside of it. You can use an <object> if there's a plugin to support your embedded data. But I think the best option for this particular use case is <script>; HTML5 now allows it to be used for "dynamic script and data blocks", and I'd say that a chunk of CSV, possibly to be rendered as a table, would count as a data block.

Here are some examples of how this could be used. I'm basing the MIME type off of RFC 4180, which includes a header property to indicate if the first line is a header. Based on Tab Atkin's example, I've also added a separator property to allow you to set the separator; this lets you use this same technique for tab separated values instead (though you probably should just use the text/tab-separated-values MIME type for that instead.

Note that in order to support fallback for browsers that have scripting turned off, I've added a CSS rule to display scripts with a type that begins with text/csv:

script[type^="text/csv"] {
        display: block;
}

This fallback mechanism works in Safari and Firefox, though it doesn't seem to work in Opera unless I open up the DOM inspector and click on one of the script elements.

Of course, we have to ask ourselves if we're actually solving any real problem here. Sure, CSV is a common format, but why is there a need to embed it in HTML? HTML has a very powerful table system built in, so creating a special purpose element (or re-purposing an existing one) for a much simpler table format doesn't seem like that much of a win; and if you need to quickly and easily turn CSV into an HTML table, it's not very hard to do so. I get 181,000 hits on Google for "csv to html", so I think that's a solved problem. And if you need to also have a machine-readable format, you can always add a link to the CSV the table was generated from in the <caption> or something like that.

So, without any particularly compelling use cases for embedding CSV into HTML, I'm not sure if this is worth all that much other than as a demo of how you can use <script> for embedding data in your own format, for processing with JavaScript.

Basic usage with no parameters

header=present

separator=\t;header=present