Building HTML client-side VS serving HTML server-side? - javascript

I always find it difficult to decide if I should render my HTML server-side or build it client-side.
Let's say I want to render a dynamic HTML dropdown with following requirements:
Shows records from a database table at page load
Must stay up-to-date (users can add/remove records from the database table using the website)
I can't decide between
Option 1
Render template with empty dropdown server-side
Populate dropdown client-side using ajax requests (JSON)
Update dropdown client-side using ajax requests (JSON)
Concern: Rendering empty elements before populating feels ugly to me
Option 2
Render populated dropdown server-side
Update dropdown client-side using ajax requests (JSON)
Concern: Why would you render server-side if you are still updating it client-side?
What solution is more commonly used in web development? Feel free to share different approaches.

This is a little opinion bases. There are schools for the server-side, and other schools for the client-side. The main reason for the later is utilizing the client machine (which are free for you) to free the server resources (which you pay for). This also makes your app more scalable.
The example that you gave is not detailed enough, and it is only one aspect. I usually use these general rules:
If there are dynamic parts of your page (e.g. dropdown, grid, popup form, etc), I use Ajax to avoid reloading the entire page.
If the HTML is very simple and/or requires further processing on the client-side, then just send JSON data from the server and build the HTML on the client-side. For example, I usually do not send error message from the server. Instead, I only send status codes (e.g. Successful, AccessDenied, Error, etc...) and I inspect those codes on the client and display the associated message. This is specially useful when different messages are displayed in different colors and styles or contain other HTML tags like links.
If it is a complex popup form or grid of data, then I send the HTML from the server. It is usually much easier and more flexible to build complex HTML on the server. Also when there are sensitive information used to build the HTML, it is usually much easier to build it on the server, otherwise you'll have to send some flags from the server or, better, you need to split your HTML building process to sections depending on permissions.
As for that very specific example in your question, I would go with the first approach (all client-side), mainly for the DRY concept (Don't Repeat Yourself). You don't want to have two pieces of code doing the exact same thing, and have to remember to update both every time you need change something.
Note though, that you don't have to send empty drop-down if you don't like it. Instead of only updating options like your example is suggesting, you can actually rebuild the entire dropdown every time. I don't particularly like this approach, especially if there are event listeners and other references attached to the dropdown, but I just wanted to say other ways to do it. This method can be useful on some scenarios, especially if the dropdown is part of a bigger section of the page that this whole section requires updating (rebuilding) every time, in which case I usually opt for sending the HTML from the server.

Your concerns are valid, each case has its advantages and disadvantages as you mentioned.
I would, personally, go with the first approach (all client-side); mainly for code maintainability. With this approach, you only have to update the HTML client-side instead of both client-side and server-side.
However, there is an argument to be made for saving that one request by server-side rendering the values. Even though it might be insignificant, there is a small performance optimization.

That depends. are you worrying about SEO?
Are you using any kind of client-side framework? I will assume that you don't, since JavaScript frameworks have there own way to do this, if you want you can read more about angular/react/vuejs which is the hottest JavaScript frameworks those days that will solve this issue.
Client-side frameworks render HTML on client-side only, and use only Ajax API to receive data from the server.
But if you don't want to use any client-side framework and do it in the "classic" way, both ways are appreciated. I tend to like the first way, this is almost how client-side frameworks do it and makes the most sense, yes you render empty table but you only render the "container" of your data, if you're bothered by how it looks visually (Showing empty list before data is fetched) you can just show loading bar or hide the table till the data is fetched.

Related

Advantages / Disadvantages to websites generated with Javascript

Two good examples would be google and facebook.
I have lately pondered the motivation for this approach. My best guess would be it almost completely separates the logic between your back-end language and the markup. Building up an array to send over in JSON format seems like a tidy way to maintain code, but what other elements am I missing here?
What are the advantages / disadvantages to this approach, and why are such large scale companies doing it?
The main disadvantage is that you have some pain with content indexation of your site.
For Google you can somewhere solve the problem by using Crawling scheme. Google supports crawling that allows you to index dynamically (without page reload) generated content of your page.
To do this your virtual links must be addresses like so: http://yoursite.com/#!/register/. In this case Google requests to http://yoursite/register/ to index content of the address.
When clicking on virtual link there is no page reload. You can provide this by using onclick:
<a href='http://yoursite.com/#!/register/' onclick='showRegister()'>Register</a>
Virtual advantage is that content of a page changed without reloading of the page. In my practice I do not use Javascript generation to do this because I build my interface in fixed positions. When page reloads user does not notice anything because elements of the interface appears in expected places.
So, my opinion that using of dynamic page generation is a big pain. I think Google did it not to separate markup and backend (it's not a real problem, you can use complex structure of backend-frontend to do that) but to use advantages of convenient and nice representation for users.
Advantages
View state is kept on the client (removing load from the server)
Partial refreshes of pages
Server does not need to know about HTML which leads to a Service Oriented Architecture
Disadvantages
Bookmarking (state in the URL) is harder to implement
Making it searchable is still a work in progress
Need a separate scheme to support non-JS users
I don't 100% understand your question, but I'll try my best here...
Google and Facebook both extensively use JavaScript across all of their websites and products. Every major website on the web uses it.
JavaScript is the technology used to modify the behavior of websites.
HTML => defines structure and elements
CSS => styling the elements
Scripting languages => dynamically generating elements and filling them with data
JavaScript => modifies all of the above by interacting with the DOM, responding to events, and styling elements on the fly
This is the 'approach' as you call it to every website on the web today. There are no alternatives to JavaScript/HTML/CSS. You can change the database or scripting language used, but JavaScript/HTML/CSS is a constant.
Consider an example of a simple form validation ...
client sends a request to a server ... the server will execute the server side code containing validation logic and in a response ...the server will send the result to the client ....
if the client has the capability to execute/process (that can be executed on the client side ...) the form ...(perform validation)..the client wont need send request to the server ...and wait for the server to respond to that request ...
i suggest you to take a look at Google Page Speed best practice http://code.google.com/intl/it-IT/speed/page-speed/ to see what are the factors that makes a good page ... generating a page with javascript seems cool because of separation of ui and logic , but it is a totally inefficient in practice

Should I send raw data or Html as an Ajax response?

I have a site written in Asp.net webforms. It uses ajax heavily.
Most forms on the site are submited with javascript. Javascript validates the input and sends it to /ajax.ashx on the server. The server processes the request and sends back a JSON response. My javascript uses the JSON to create html, which it inserts into the Dom.
I'm making a new version of my website written using asp.net MVC3. I've been looking at tutorials on this subject, and some of them recommend doing ajax in a different way. Rather than sending data and then building + inserting html with javascript, they create html at the server, and use javascript only to insert it into the Dom. For instance, in this tutorial.
Which way should I use? Using the new method will be quicker, but is it better?
That's a subjective question. Both approaches are possible and there is no better way. There are pros and cons of each approach.
Building the HTML on the server is easier and will require you less efforts but consumes more bandwidth compared to the first approach.
If you decide to go the first way you could use some client side templating framework which might help you simplify the generation of DOM elements on the client.
Creating html code directly into the server and injecting it with an ajax call is very fast and simple, the real problem is that in that way your service is bound to be used with that specific application. By sending RAW data you allow any app to use that data in any way, without bounding it to a specific application.
returning json feels more flexible to me; you can change what happens with your json response, like the layout it results in. If you return html you return data mixed with layout. This doesn't feel right to me.
I believe it is better to separate the layout from the actual data. That is why you should pass data between your scripts and not HTML.
If you go about it sending HTML, consider that you would have to build valid HTML and CSS, which might not sound hard at first but then you'll start using CSS that is not loaded in the file calling the ajax, etc.
Always separate content (data) from layout. That's why there is HTML and CSS, to separate layout from data. So why mess things up by mingling HTML between data?
Building the html serverside will probably be faster and not bog down the client which is important. Rendering data into HTML with javascript takes time and not every browser is fast with js (i.e. older versions of IE) so things can slow down if you're doing a lot of this.
Like previous posters said, it's kinda subjective because it depends on how much you're offloading to the client. I'm of the opinion that if you can do things serverside, you should.
If you are going to be using this service to return JSON to other applications/clients, then it's probably a good idea to just leave it as JSON and let the client do what it needs on their side.

Are javascript templates only useful for inserting small items into the DOM?

I recent came across Javascript templates and have become quite intrigued.
I am building a large PHP application using the MVC pattern. Templating is handled by the rather awesome Twig.
I recently came across a javascript implementation of twig.
I have also read quite a bit about using javascipt template engines.
Now, in my application, the application generates a the full page for standard requests as fallback for users without javascript. For AJAX requests, it can generate the content part of the page (no <head>, <body> etc).
The ajax response object is currently just a the rendered HTML content, which is then inserted into DOM.
Should I instead return a response object containing a compiled javascript template and the objects to be inserted into the template? What are the benefits of doing that?
From the posts I have read, the javascript templates were only small snippets representing a small part of a page, for example displaying a comment on a blog post during the instant that the user has submitted it.
Are javascript templates only useful for inserting these sort of small "pieces" in a page?
Yes
A recent project I was on got "client-side template fever" and we used the dang things for every single template.
With every template library I've used (which is two or three), the error messages you get are not very good. If you have a huge template that operates on a fair amount of data, you'll quickly find the u.foo is null or not an object error message increasingly frustrating.
The best-practices I've settled on is:
Return a full HTML snippet (from the server) if it's a template that is seldom loaded. If you are only loading that HTML once on a page, then you might as well send it down populated right? This also encourages you to keep your logic up on the server, where it probably belongs.
Use client-side templates for small, repeated templates. Your blog comment example is probably a good one. I've found the most success when my client-side templates are pretty small (< 10 lines)
Use a logic-less template engine. The more logic allowable in a template, the harder they are to read/maintain. Plus, some of that logic should probably be in your business layer, not down in some JavaScript template. In other words, they force you to separate your presentation from your logic (which is good).
PS: It is cool that both your client and server-side templates could use the same templating engine. This will make developers on your project much more productive.
Depending on the scale and requirements of your application, you should take into considerations the following:
don't go rampant on Ajax; Ajax is not WebSockets, so use it sparingly. Plus, client-side execution speed is always key; AJAX is slow when compared to dumping as much resources as possible + using them when you need them; for example, you can send to javascript userdata = {name:'xxxx',address;'yyyy', ...} and using that, instead of requesting name and address via AJAX only when you need them.
it is recommended to use a global PHP var $sendData (or something like that) and right after plasting HTML, you send the $sendData with an easy <script>data = <?php echo json_encode($sendData); ?></script>
javascript templates add up to execution speed. which makes it reasonable to do the alternative, that is, separating everything that is dynamic and caching static resources like javascript functions
you can't, and I quote return a response object containing a compiled javascript template, not without residing to some server-side javascript engine that does the compile job prior to returning it
for your personal welfare, it will always boil down to how fast, easy and painlessly you respond to maintaining the application; there's no point in using super beta experimental frameworks, ports and kits over which you have limited control
Work smart, not hard.
Good luck mate.
You could also look into the Distal http://code.google.com/p/distal templating engine.

Render partial view on the server or send json data and render template on the client

I was wondering what would be a good approach (or recommended approach) to render partial views in a web application.
I have a requirement where I need to load data into an already rendered page using AJAX, sort of like a "Load more..." link at the end of the page which grabs more information from the server and renders it to the bottom of the page.
The two options I am playing with at the moment for the AJAX response are
Return a JSON representation of the data, and use a client side template library, (e.g. jQuery templates) or just plain javascript to turn the JSON into HTML and append to the bottom of the page
Render the partial view on the server (in my case using grails' render template:'tmplt_name') and send it across the wire and just append the result to the bottom of the page
Are there other ways to do this? If not, given the above options which would be better in terms of maintenance, performance and testability? One thing I am certain about is that the JSON route will (in most cases) use up less bandwidth than sending html across the wire.
This is actually a really interesting question, because it exposes some interesting design decisions.
I prefer rendering partial templates because it gives my applications the ability to change with time. If I need to change from a <table> to a <div> with a chart, it's easy to encapsulate that in a template. With that in mind, I view almost every page as a aggregate of many small templates, which could change. Grails 2.0 default scaffolding has moved towards this type of approach, and it's a good idea.
The question as to whether they should be client-side templates or server-side is the crux of the issue.
Server side templates keep your markup cleaner on initial page load. Even if you use something like Mustache of ICanHazJS, you kinda sorta need to have an empty element in the page (something with your template), style it appropriately, and work with it in Javascript in order to get update your info.
Drawbacks
"chatty" applications
larger envelopes across the wire (responses include HTML, which may be considered static)
slower UI response time
Benefits
Good for people with lots of server side language experience
Maybe easier to manipulate or modify in a server-side environment (e.g. return a page embedded with multiple templates, which are programmatically loaded and included)
Keeps most of the application stuff "in one place"
Client-side templates can really reduce server-load, however. They make an application "less -chatty", in that potentially you could minimize the number of calls back to the server by sending larger collections of JSON back (in the same number of bytes, or fewer, that would be taken up by HTML in a server-side template scheme). They also make UI experience really fast for users, as clicking an "update" link doesn't have to do an AJAX round trip. Some have said:
Anthony Eden #aeden 10 Dec Reply Retweeted Favorite ยท Open
the future of web apps: requests are handled by functions, logic is always asynchronous, and HTML is never generated on the server.
Drawbacks
Not great for SEO (un-semantic extraneous UI elements on initial page load)
Requires some Javascript foo (to manipulate elements)
Benefits
- Responsive
- Smaller envelopes
Trends seem to be moving towards client side templates, especially with the power exposed by HTML5 additions (like <canvas>)...but if leveraging them requires you to rely on technologies you're not extremely familiar with, and you feel more comfortable with Grails partials, it may be worthwhile to start with those and investigate refactoring towards client side templates based on performance and other concerns later.
in my view the second option rendering partial is better because if you get a json data you are supposed to manipulate it like set style, create elements, set values and similar thing as per the need just after you get ajax response in javascript but if you render partial, you can design your view in that partial before and keep ready and just import using ajax call so there is no responsibility of handling the response data.
I would say it depends on how much data you're sending across the wire as you put it. If you're implementing a "load more" feature then it seems like you wouldn't want to take 5 seconds to load something. Google images is a good example of how quick that feature should be. If you know you'll never have that much data then rendering the partial on the server might be cleaner, but if you're requirements change then it's a hassle to go back to the first approach. So in short, I'd say the first approach allows for more disaster control as far as how long a load more takes to load a large amount of data. I'd say it's also general good practice to take load off server when you can, even if it's a little inconvenient on the client side for the developer.

Growing into JavaScript as an integral part of the front-end vs. 'DHTML'

More of a general question here.
At the moment a lot of the projects I work on utilize server-side views to render the user interface, and spruce it up with some JavaScript here and there. That is all fine and dandy for smaller projects, but lately it seems like the .js files are growing rather large in size, and the stacks upon stacks .live and .bind jQuery calls just don't seem to cut it anymore.
What are good ways to blend JavaScript into the view and, perhaps, the controller of a web application? For the Java-driven websites I found DWR to be quite useful, but a lot of times user initiated events require controller logic, which is starting to become overwhelming and confusing when it's part of the many lone functions included on the pages.
I considered a completely AJAX-driven template engine but that seems to be a bit extreme and will likely be a pain in the butt for anyone to use. Cloning the functionality of the existing backend classes, on the other hand, seems redundant.
What is a good "middle ground" approach used by web apps out there, those that aren't entirely AJAX free nor completely JavaScript driven?
EDIT:
Perhaps I'll provide an everyday example of a problem. Say I'd like to provide the user with a modal dialogue confirming or denying something:
"Your picture is uploaded but looks terrible. You need a new 'do." (OK | What?)
Now, in one scenario, that dialogue could pop up as a result of uploading an image with a page refresh, in which case the server-side view will render it. In another scenario, it might appear after uploading the image via AJAX, in which case it'll probably be triggered by JavaScript on the page. In both cases we need to access the dialogue creation code, and I can't so far think up a way to have, say, a Dialog class which would work the same in both cases.
I'm certainly not an expert in this realm, but in the past have worked with projects utilizing RESTful services which seemed to fit the 'AJAXY' world of web site development nicely. I can't say it'd be ideal for web apps, but worked great for content-rich presentational sites. It seems like it'd fit your need for multi-presentational formats nicely via custom templates. So, the service could call the pictureUpload service using a HTML page template, or it could call the service and request the AJAX component template.
I've been working recently with JavascriptMVC (2.0) for an internal company app. It has its warts, but the overall architecture is good and allows you to create "controller" JS classes. Each controller "owns" a subset of the DOM tree (or if you prefer, a visual part of the page) and responds to events within that zone and uses EJS templates (the "view" part) to alter areas under it. It nicely abstracts what would otherwise be a lot of $(...).bind() and $(...).live() calls into an OOP model.
In my case, our interface is almost 100% JS-driven due to the constraints around the project, but there's no reason you can't mix-n-match.
Now, in one scenario, that dialogue could pop up as a result of uploading an image with a page refresh, in which case the server-side view will render it. In another scenario, it might appear after uploading the image via AJAX, in which case it'll probably be triggered by JavaScript on the page
Here's how I'd do it in a way that works even with Javascript disabled:
Server-side outputs an HTML upload form. The plain-HTML form will submit to another PHP page.
A snippet of Javascript runs when the page finishes loading, looking for that form.
The javascript creates a HairdoUploadController instance, passing in the <form>...</form> to the constructor.
The controller "takes over" the form, using JQuery selectors to alter the styling and to trap the form submitting events.
The controller adds a new div and associates it with a (initially hidden) Jquery-UI Dialog.
When the form is submitted, the controller instead makes an AJAX call, to a slightly different URL than the plain form.
The results of the AJAX call are pushed into the Dialog's div, and the dialog is displayed.
You can throw all logic at the server, and assume a dumb client that displays whatever the server sends.
There are two scenarios:
Non-Ajax Request
Ajax Request
The only difference between them is that, in the first one you're rendering more content than just the modal dialog. There's no reason why you can't have a Dialog class on the server which spits out the HTML representation of the dialog, and is used for both types of request. Then in the AJAX call, you would simply add the server's response into the DOM.
Like you said, it can be problematic sharing UI creation logic on both client and server side, so it's better to choose one and stick with it. In the above case, all logic is pushed to the server. Read up more about AHAH.
It sounds like Google Web Toolkit might be what you're looking for.
It allows you to write client-side
applications in Java and deploy them
as JavaScript.
Presumably then you could write the code once in Java and use it in both places, although I've never used GWT myself.
In my own framework that I'm developing, I'm basically forcing developers to write the code twice. Once in the native language, and once in JavaScript. I make them fill in a function which returns the JS, and then it can be called automatically where it's needed. But all the code is contained within one class so at least you don't have the logic spread all over the place, and you can quickly compare if they are functionally equivalent. For things like regular expressions, it can normally be written just once and then passed to JS (I use it to validate once on the client-side, and then again on the server-side).
I have found myself recently using my server side code (ASP.Net MVC in my case) as a means to provide re-use of my layout components (master files), and small encapsulated bits of UI (partial views), and doing a fair amount of work in javascript. In this particular case I'm still pretty early in my UI work, but with jQuery and jQuery UI I've got a lot of functionality in a very small footprint.
I think one of the challenges to having a mixed solution is figuring out where to put the various bits of logic. After that the rest of it probably goes to figuring out how to re-use as much of your javascript and css code as possible. I still haven't figured out how to manage the various javascript artifacts I end up with (though the Google CDN relieves a lot of that by providing jQuery, jQuery UI, ans the jQuery UI CSS resources).

Categories

Resources