Since HTML data
attribute allows adding any custom data, I wonder if it is a good idea to include a set of JSON
list as a data
attribute?
Technically you can, and I have seen several sites do this, but another solution is to store your JSON in a tag and put a reference to the script tag in the
data
attribute. This is a better solution than just storing the data as a JS object in an actual script if the data is rendered to the page server-side, but there are CSP restrictions on inline script tags, for example.
HTML
JS
$(function () {
var dataId = $("#x").data("data-id");
var dataTag = $(dataId);
var dataJson = dataTag.html(); // returns a string containing the JSON data
var data = JSON.parse(dataJson);
...
});