Search code examples
javascriptplatform-agnostic

How do I send a value with my HTML that is accessible from Javascript?


Often the Javascript on a webpage will need to be able to access variables that are known on the server. For example, the user's username. Suppose that we don't want to make a JSON/XML request as that would increase the complexity unnecessarily and also the number of page hits. We want to send the data along with the html/Javascript.

One way to send the data would be to inject it into the Javascript.

var x={{username}};

Another idea would be to create a meta item in the head and store the data there and then use jQuery (or equivalent) to retrieve it.

Is either of these methods preferable to the other or are there any other methods that I should consider?


Solution

  • Is either of these methods preferable to the other or are there any other methods that I should consider?

    I don't think there's a single right answer, and certainly I've heard lots of contradictory opinions on this subject, but choosing from the two methods you mention I'd go with injecting the values into JavaScript because I find it easier.

    But since you asked for other suggestions you can kind of combine the two ideas: instead of meta items, your server-side code can just insert a single <script> element in the <head> to store the data in a variable that can then be accessed directly from any of your other scripts (including scripts in multiple source files). You can stick all of your data in a single object to avoid lots of globals:

    <html>
    <head>
    <script>
       var dataFromServer = { /* all your server data here */};
    </script>
    <script type="text/javascript" src="somelibrarycript.js"></script> 
    <script type="text/javascript" src="someotherscript.js"></script>
    <script>
       if (dataFromServer.someProperty) {
          // someProperty provided above so do something with it...
       }
    </script>
    </head>
    etc...
    

    This approach has the added advantage that the server-side code is essentially just producing JSON (that becomes an object literal if included directly in the page source) so if you later decide to start using some Ajax you'll already be almost there.