i need to send some data with the html page to the browser, which will be consumed by javascript (things like the user’s details, etc.).
i see two ways to do it, and i wonder which one is better (blocks the browser less, performs better):
1.inline script in the html:
<script>var userData = {username:'joe',age:42,pet:'dog'}</script>`
2.data attribute in the html:
<div id="user-data" style="display:none" data-username="joe" data-age="42" data-pet="dog"></div>` and code in external javascript file: `function getUserData() {..this extracts the data from the div and caches it...}
i know that inline script-tags will block the browser, on the other hand they will be probably parsed much faster than when i will do it in javascript later.
One school of thought is to consider using
<script type="application/json"></script>for data you want to send along with your page, if you really don’t want to use ajax. It’s pretty easy to then write a script which grabs all json from the page as additional page data when the page loads. The benefits being you have deferred execution, you do not inject data directly into global scope and you are not generating JavaScript on the server side either.