views:

131

answers:

5

Now a community wiki!

I want to make it clear first: This isn't a question in relation to server-side Javascript or running Javascript server side. This is a question regarding rendering of Javascript code (which will be executed on the client-side) from server-side code.

Having said that, take a look at below ASP.net code for example:

hlRemoveCategory.Attributes.Add("onclick", "return confirm('Are you sure you want to delete this?');")

This is prescribing the client-side onclick event on the server-side.

As oppose to writing Javascript on the client-side:

$('a[rel=remove]').bind('click', function(event) {
    return confirm('Are you sure you want to delete this?');
}

Now the question I want to ask is: What is the benefit of rendering javascript from the server-side code? Or the vice-versa?

I personally prefer the second way of hooking up client-side UI/behaviour to HTML elements for the following reasons:

  • Server-side does what ever it needs to already, including data-validation, event delegation and etc; and
  • What server-side sees as an event is not necessarily the same process on the client-side. i.e., there are plenty more events on client-side (just look at custom events); and
  • What happens on client-side and on server-side, during an event, could be completely irrelevant and decoupled; and
  • What ever happens on client-side happens on client-side, there is no need for the server to know. Server should process and run what is given to them, how the process comes to life is not really up to them to decide in the event of the client-side events; and so on and so forth.

These are my thoughts obviously. I want to know what others think and if there has been any discussions on this topic.

Topics branching from this argument can reach:

  • Code management: is it easier to render everything from server-side?
  • Separation of concern: is it easier if client-side logic is separated to server-side logic?
  • Efficiency: which is more efficient both in terms of coding and running?

At the end of the day, I am trying to move my team to go towards the second approach. There are lot of old guys in this team who are afraid of this change. I just wish to convince them with the right facts and stats.

Let me know your thoughts.

UPDATE1: It looks like all of us who have participated in this post have common thought; Good to know that there are others who think alike. Now to go convince the guys ;) Thanks everyone.

+2  A: 

Your second example is vastly superior to the first example. Javascript is your behaviour layer and should be separate from your semantic markup (content) and CSS (presentation). There are a number of reasons this is better architecture:

  • Encourages progressive enhancement. As you mentioned, the backend code should work correctly in the absence of JS. You cannot rely on your clients having JS available. This way you build it once without JS and then can enhance the experience for those with JS (e.g. by adding clientside validation as well as serverside validation so that the client can get instant feedback)
  • Cleaner markup. Normally reduced download size. One reusable selector in a separate JS file that can be cached and shared between pages vs. a handler on each element.
  • All of your JS in one re-used place. e.g. if your code was opening a popup window and you decided to change the dimensions of the window you would change it once in the code in the JS file vs. having to change it on every individual inline handler.

There are lots of other arguments and reasons but they should get you started...

Also, from your example it appears that you have a normal link in your document which can delete content. This would also be a bad practice. Anything that deletes or updates content should be done on a POST (not GET) request. So it should be the result of submitting a form. Otherwise e.g. googlebot could accidentally delete all of your content by just crawling your page (and search engine robots don't execute JS so your alert wouldn't help there)

vitch
RE: delete, it's theoretical of course :) but point taken.
davidhong
+1 for "progressive enhancement"
davidhong
A: 

For the code in your example it doesn't really matter. The code isn't using any information that is only available at the server side, so it's just as easy to bind the event in client side code.

Sometimes you want to use some information that is available at the server side to decide whether the event should be added or not, or to create the code for the event, for example:

if (categoryCanBeDeleted) {
  hlRemoveCategory.Attributes.Add(
    "onclick",
    "return confirm('Are you sure you want to delete the " + categoryType + "?');"
  );
}

If you would do this at the client side, you have to put this information into the page somehow so that the client side code also has access to it.

Guffa
I would argue this is still bad practice. Instead you should set e.g. a css class on the element and use that in your clientside selector Or like in the original code in the question you could only set the rel to remove where it was a link that should do the removing (with the caveat in my answer about removing anything from a GET link anyway)
vitch
I like the data attributes in HTML5 for this purpose. You can embed a message on the element itself. For example: `<a data-delete="true" data-warning="Are you sure you want to delete your account permanently?">Delete Account</a>`. Then Javascript can pickup all elements with an attribute of `data-delete` and use the embedded message that is highly customizable. Rails 3 is betting big on something like this to cut down the Javascript clutter.
Anurag
I agree with vitch and Anurag here. I think there are plenty of examples on this post already.
davidhong
@davidhong: Yes, I know your opinion, but you asked for other's thoughts about it. Seems I was wrong for thinking...
Guffa
Difference is that we've successfully explored options and come to a conclusion atleast on this part. So no one was wrong, we've all gained knowledge =)
davidhong
+3  A: 

The two biggest differences i can think of up front are:

  • you lose the client side caching you would get if the javascript was in a separate js file
  • if you need to change your javascript, you have to recompile (extrapolate this to what happens after you have released your product: if you have to recompile then you need to redistribute binaries instead of just a modified js file)
  • it is easier to use the VS debugger if the javascript is in a separate file; you can just set a break point in that file, if you are generating the code server side then you have to use the running documents feature, find your generated code and then add the breakpoint, and that breakpoint has to be manually added everytime you re-run your app. Following on from that, if the code is in a separate file, then you can just make your tweak to the javascript code, F5 your browser page, and keep on debugging without having to stop and restart the debugger.

It should be mentioned that sometimes you have to insert js code from the server - for example if the bulk of your code is in a separate js file and you need to insert control identities in to the page for that code to work with. Just try to avoid that situation if possible.

slugster
RE: Control identities - nowadays, using frameworks such as jQuery, identifying controls on client-side is such an easy job. Either through a css class attribute or any other custom attribute such as data-tooltip="true" (obviously on a non-XHTML page). And I personally prefer custom attributes as it offers more flexibility.And I completely agree with your point about re-compilation of code for a small client-side change! So annoying.
davidhong
+1  A: 

Looks like you already know what to do. Rendering it on the server side is a bad idea.

The simple reasoning being you're Javascript lives both on the server side pages as well as in separate Javascript files (assuming you are using Javascript at all). It can become a debugging nightmare to fix things when everything is everywhere.

Were you not using any other Javascript besides what the server side scripts generate, it would probably be fine and manageable (forget what the unobtrusive movement says).

Secondly, if you have 100 links on the page, you will be repeating that same code in 100 places. Repetition is another maintenance and debugging nightmare. You can handle all links on all pages with one event handler and one attribute. That doesn't even need a second thought.

<Rant>

It's not easy to separate HTML and Javascript, and even CSS especially if you want some AJAX or UI goodness. To have total separation we would have to move to a desktop application model where all the front-end code is generated on the client side programmatically using Javascript, and all interaction with the server gets limited to pure data exchange.

Most upstream communication (client to server) is already just data exchange, but not the downstream communications. Many server-side scripts generate HTML, merge it with data and spit it back. That is fine as long as the server stays in command of generating the HTML views. But when fancy Javascript comes onboard and starts appending rows to tables, and div's for comments by replicating the existing HTML structure exactly, then we have created two points at which the markup gets generated.

$(".comments").append($("<div>", {
    "id": "123",
    "class": "comment",
    "html": "I would argue this is still bad practice..."
}));

Maybe this is not as big a nightmare (depending on the scale), but it can be a serious problem too. Now if we change the structure of the comments, the change needs to be done at two places - the server side script and templates where content is initially generated, and the Javascript side which dynamically adds comments after page load.

A second example is about applications that use drag and drag. If you can drag div's around the page, they would need to be taken off the regular page flow, and positioned absolutely or relatively with precise coordinates. Now since we cannot create classes beforehand for all possible coordinates (and that would be stupid to attempt), we basically inject styles directly in the element. Our HTML then looks like:

<div style="position: absolute; top: 100px; left: 250px;">..</div>

We have screwed up our beautiful semantic pages, but it had to be done.

</Rant>

Semantic, and behavioral separation aside, I would say is basically boils down to repetition. Are you repeating the code unnecessarily. Are multiple layers handling the same logic. Is it possible to shove all of it into a single layer, or cut down on all repetition.

Anurag
Nice rant. One more addition: even if the (serverside) generated JavaScript code is dynamic and depends on application state, seperating into a different .js file and using JSON to export the server-side variables to the page-javascript is a better solution than to generate different code for each branch.
Konerak
A: 

You and the other people answering the question have already listed reasons why it is better not to having the server side code spit intrinsic event attributes into documents.

The flip side of the coin is that doing so is quick and simple (at least in the short term).

IMO, this doesn't come close to outweighing the cons of the approach, but it is a reason.

David Dorward