In addition to the plain old object literal method given in other answers, if the value you want to pass to the client is about a specific DOM element (or there is a DOM element that represents the logical object that the value is about), you can put the value in a data attribute:
<div id="videoplayer" data-startplayingat="1:02">HTML Content</div>
This is accessible as an entire attribute, data-startplayingat
, or in modern browsers there is the dataset
attribute. jQuery syntax is $('#videoplayer').data('startplayingat')
.
The official W3C spec on data attributes explains all this.
Here are a few interesting highlights:
- The name must not use upper case letters, and must be XML compatible.
- The
dataset
attribute converts dashes, such that a name like start-playing
will become startPlaying
.
One potential drawback for the object literal method (which I like and have used myself) is that if you want the object in a .js file, then normally static javascript files have to be run through your dynamic parser--which will cause a potentially small (but still present) performance loss. Putting the object declaration into a <script>
tag in an HTML file works around this, but then you can have script load order issues to deal with.