Question

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?

Was it helpful?

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.

OTHER TIPS

I would just have a element in the head which declares a well-named global object containing your information. Something like :

<script type="text/javascript" >
    this.blah = this.blah || {};
    this.blah.userinfo = this.blah.userinfo || {};

    this.blah.userinfo = {
        "username" : "UserName42"
        "gender" : "Male"
    };
<script>

The top two lines just initialise your global object. Since it's global, we use "blah" to namespace it.

What you are suggesting is totally fine. For example Jeremy Ashkenas, creator of CoffeeScript, Underscore.js and Backbone.js suggests to do exactly the same in Backbone docs

<script>
  Accounts.reset(<%= @accounts.to_json %>);
  Projects.reset(<%= @projects.to_json(:collaborators => true) %>);
</script>

I think that a question is a bit convoluted, since, in my experience, you rarely rely on static/pre-created HTML pages for sites that have accounts, user privileges etc.

Normally, such a site/application relies on some sort of "Server Pages" technology - ASP, JSP, PHP (or manages all of this through AJAX requests) - which would allow you to write some sort of tag/server code similar to <%=request.getAttribute("userName")%> - that, when compiled/interpreted by the server, will inject the username for you in the place in your page you intend it to be.

If, for some reason, you claim that it's not the case in your application and you deliver pure pre-created or static HTML to your users - then, indeed you would have to do one of the following:

1.AJAX request that retrieves the username

I think that your argument that

that would increase the complexity unnecessarily and also the number of page hits

is not a valid one. Correctness of use of technology should prevail over (perhaps non-existent) performance gain. I also don't see that as a complexity increase, on the contrary - you could separate the "user" logging in part into a module and reuse it elsewhere.

2.Inject JavaScript (or use meta-tags)

and this one I am not entirely sure how would you do that and maintain your page after that...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top