Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
183
rated 0 times [  188] [ 5]  / answers: 1 / hits: 33337  / 12 Years ago, fri, january 18, 2013, 12:00:00

I would like to embed JSON in HTML. The most elegant solution I have found makes use of the script-tag and the mime media type application/json.



<script id=data type=application/json>
{
foo : bar
}
</script>


Is this the standard way of embedding JSON? If not, are there any risks with the above solution?



Reasons for using inline JSON (instead of a JSON-P service):




  • Small amounts of JSON-data

  • Less HTTP-requests

  • Preference for inline-JSON to data in HTML-attributes



[UPDATE] Reason for embedding json.



I have a gallery widget for a website with very high traffic. The gallery can consist of a 100 images or more. I am only showing one image at a time and the rest of the images will be lazy loaded. However the information (image src) to all images will be rendered in the html on page load. There are various ways to render the image information in the html. Instead of using JSON I could also use html data attributes as shown below:



<li class=image data-src=image-path.jpg>
<!-- image tag will be created here using javascript -->
</li>


Will result in:



<li class=image image-loaded data-src=image-path.jpg>
<img src=image-path.jpg />
</li>


The disadvantage with the above solution is the extra markup. I would rather use JSON and a Javascript-Templating engine such as doT.js.


More From » html

 Answers
9

Reasons for using inline JSON (instead of a JSON-P service)




You can inline JSON-P as well. OK, you just call that method inline script, but it has the advantages of both :-)


[#80783] Thursday, January 17, 2013, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
lesterluiss

Total Points: 513
Total Questions: 104
Total Answers: 106

Location: Honduras
Member since Sat, Jul 24, 2021
3 Years ago
;