Complex client-side logic -- better to move to the server side? - javascript

I'm working with a third-party search API, and am rather enjoying keeping pretty much the entire application on the browser side. The XML is digested entirely with javascript, and I'm rendering complex result objects dynamically, using a javascript templating engine. There are few page reloads happening, and lots of fancy javascript going on.
It feels clean to me to keep everything on the javascript side. It's going to make deployment much easier, and it's nice to have all my code in one place. I'm trying to be just as rigorous about coding well with javascript as I would were I coding in Java, and so far things seem to be working pretty well. I'm making an effort to work TDD style, using YUI test, and am optimistic that this will make the inevitable cross-browser bugs easier to catch and fix. The code size is not minuscule, but it's not too bad, and I plan to minify it before deployment, which should reduce it to about 2/3 of what it is now.
Are there drawbacks I'm not considering? Any other proponents of front-siding application logic here?

There are few page reloads happening, and lots of fancy javascript going on.
There is one large drawback to relying too heavily on JavaScript. Remember that whenever you design a web application you should base it on the premise that the user doesn't have JavaScript enabled - although this is a minority there are still a lot of users who don't have it enabled for whatever reason, and if your application relies too heavily on JavaScript in its fundamental operation, then it won't be accessible to those who disable JavaScript.
Whenever I write pages that have JavaScript or AJAX functionality I always make sure to have a secondary way of information being displayed or submitted, in case JavaScript is turned off on the user's browser. Of course this often isn't necessary for aesthetics - menu items sliding along a menu bar when clicked and the page is changed won't affect the core functionality of the page if JavaScript is turned off and they simply act like static links; however for core features such as inputting data and having results displayed, you should ensure to provide backup methods that are employed when JavaScript is not enabled.

You should use AJAX only when it actually improves user experience. It is very annoying when trivial functionality requires JS needlessly. I would expect (no idea if it's the case for your app) to be able to enter a search, get the results, and page through the results all without JS.
There's nothing wrong with "extras" like AJAX paging or search refinement. But the essentials should be there either way.

Related

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).

Javascript Ajax Graceful-degradation, with Different Pages?

I'm starting to give a little more attention to making my javascript and ajax degrade gracefully. Which is more recommended:
working on incorporating the graceful degradation into your existing code (can be tricky)
or
developing a different sets of pages for the non-js users.
I'm leaning towards the different sets of pages, because I feel it's easier and I get to deliver the best possible results for each user type (js-enabled or js-disabled). Do you agree with me, and if not, why do you disagree?
I'm also worrying about hacking attempts. For example hacker gets to the js-enabled version, then disables his js. Any thoughts on this point? I don't know much about hacking, but can this be a security concern if I go with the separate versions?
Thanks in advance
Though it doesn't work well for existing sites, often it's more useful to use the Progressive Enhancement paradigm: build the site so it works with no special add-ons, then start layering your awesomeness on top of that.
This way you can be sure it works from the ground up and everyone (including those who use screen readers, those who turn off images or stylesheets, and those who don't use javascript) can all access your site.
For an existing site, however, it will depend on what functionality the ajax is delivering. In general you should strive to mirror all the ajax functionality with js disabled. If you have security holes in your js version, than you probably will in your non-js version too. AJAX can't get to anything that can't be accessed via ordinary URL.
Developing two separate sets of pages, one for JS enabled and one for non-JS, is obviously a lot of work, not only initially, but also as your application keeps evolving. If that doesn't bother you too much, I think that's the way to go. I think you are right about same-page graceful degradation being very tricky sometimes. Sometimes this is just because of the layout: With JS enabled, you can simply hide and show elements, where as without JS: where to put everything? Separate sets of pages can help keep page structure cleaner.
About hacking attempts: You can never, never, never rely on client-side JavaScript validation. Everything has to be checked (or re-checked) server-side, and your server-side code may make no assumptions whatsoever on the user input. Therefore, I think the scenario of someone de-activating JS while using the application is irrelevant. Try to keep the expected user input uniform for the non-JS and the JS versions, validate it properly, and you're good.
You'll probably want to check out jQuery Ajaxy. It lets you gracefully upgrade your website into a full featured ajax one without any server side modifications, so everything still works for javascript disabled users and search engines. It also supports hashes so your back and forward buttons still work.
It's been implemented on these two sites (which I know of) http://wbhomes.com.au and http://www.balupton.com

One page only javascript applications

Have you experimented with single page web application, i.e. where the browser only 'GETs' one page form the server, the rest being handled by client side javascript code (one good example of such an 'application page' is Gmail)?
What are some pro's and con's of going with this approach for simpler applications (such as blogs and CMSs)?
How do you go about designing such an application?
Edit: As mentioned in the response a difficuly is to handle the back button, the refresh button, bookmarking/copying url. The latter can be solved using location.hash, any clue about the remaining two issues?
I call these single page apps "long lived" apps.
For "simpler applications" as you put it it's terrible. Things that work OOTB for browsers all of a sudden need special care and attention:
the back button
the refresh button
bookmarking/copying url
Note I'm not saying you can't do these things with single-page apps, I'm saying you need to make the effort to build them into the app code. If you simply had different resources at different urls, these work with no additional developer effort.
Now, for complex apps like gmail, google maps, the benefits there are:
user-perceived responsiveness of the application can increase
the usability of the application may go up (eg scrollbars don't jump to the top on the new page when clicking on what the user thought was a small action)
no white screen flicker during the HTTP request->response
One concern with long-lived apps is memory leaks. Traditional sites that requests a new page for each user action have the added benefit that the browser discards the DOM and any unused objects to the degree that memory can be reclaimed. Newer browsers have different mechanisms for this, but lets take IE as an example. IE will require special care to clean up memory periodically during the lifetime of the long-lived app. This is made somewhat easier by libraries these days, but by no means is a triviality.
As with a lot of things, a hybrid approach is great. It allows you to leverage JavaScript for lazy-loading specific content while separating parts of the app by page/url.
One pro is that you get the full presentation power of JavaScript as opposed to non-JavaScript web sites where the browser may flicker between pages and similar minor nuisances. You may notice lower bandwidth use as well as a result of only handling with the immediately important parts that need to be refreshed instead of getting a full web page back from the server.
The major con behind this is the accessibility concern. Users without JavaScript (or those who choose to disable it) can't use your web site unless you do some serious server-side coding to determine what to respond with depending on whether the request was made using AJAX or not. Depending on what (server-side) web framework you use, this can be either easy or extremely tedious.
It is not considered a good idea in general to have a web site which relies completely on the user having JavaScript.
One major con, and a major complaint of websites that have taken AJAX perhaps a bit too far, is that you lose the ability to bookmark pages that are "deep" into the content of the site. When a user bookmarks the page they will always get the "front" page of the site, regardless of what content they were looking at when they made the bookmark.
Maybe you should check SproutCore (Apple Used it for MobileMe) or Cappuccino, these are Javascript frameworks to make exactly that, designing desktop-like interfaces that only fetch responses from the server via JSON or XML.
Using either for a blog won't be a good idea, but a well designed desktop-like blog admin area may be a joy to use.
The main reason to avoid it is that taken alone it's extremely search-unfriendly. That's fine for webapps like GMail that don't need to be publically searchable, but for your blogs and CMS-driven sites it would be a disaster.
You could of course create the simple HTML version and then progressive-enhance it, but making it work nicely in both versions at once could be a bunch of work.
I was creating exactly these kind of pages as webapps for the iPhone. My method was to really put everything in one huge index.html file and to hide or show certain content. This showing and hiding i.e. the navigation of the page, I control in a special javascript file where the necessary functions for handling the display of the parts in the page are.
Pro: Everything is loaded in the beginning and you don't need to request anything from the server anymore, e.g. "switching" content and performing actions is very fast.
Con: First, everything has to load... that can take its time, if you have a lot of content that has to be shown immediately.
Another issue is that in case when the connection goes down, the user will not really notice until he actually needs the server side. You can notice that in Gmail as well. (It sometimes can be a positive thing though).
Hope it helps! greets
Usually, you will take a framework like GWT, Echo2 or similar.
The advantage of this approach is that the application feels much more like a desktop app. When the server is fast enough, users won't notice the many little data packets that go back and forth. Also, loading a page from scratch is an expensive operation. If you just modify parts of it, the browser can keep a lot of the existing model in memory and just change the parts that changed.
Another advantage of these frameworks is that you can develop your application in pure Java. This means you can debug it in your IDE just like any other Java app, you can write unit tests and run them automatically, etc.
I'll add that on slower machines, a con is that a large amount of JavaScript will bring the browser to a screeching halt. Since all the rendering is done client-side, if the user doesn't have a higher-end computer, it will ruin the experience. My work computer is a P4 3.0GHZ with 2 GB of ram and JavaScript heavy sites cause it to chug along slower than molasses, which really kills the user experience for me.

When NOT to use AJAX in web application development? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
I'm building a web application with the Zend Framework. I have wanted to include some AJAX type forms and modal boxes, but I also want my application to be as accessible as possible. I want my application to be enhanced by AJAX, but also fully functional without AJAX.
So as a general guideline...when should I not use AJAX? I mean, should I bother making my application usable without AJAX? Or does everyone have AJAX enabled browsers these days?
If you mean "accessible" in the ADA sense, AJAX is usually a no-no - your site should provide all its content and core functionality using only standard (X)HTML and CSS. Any javascript used should merely extend the core functionality, and your site should be coded to work elegantly in the absence of a javascript-enabled browser.
Examples: if you want a user to click on a thumbnail and get a full-size version of the image as a result, you can make the thumbnail a link. Then, the onclick event will fire a JQuery method that cancels the navigation behavior of the link and pops up a JQuery floating div to show the image on the current page. If the user's browser doesn't support JavaScript, the onclick event will never fire, and the user will be presented the image in a new page. The core functionality is the same with or without scripting.
EDIT: Skeleton example, sans JQuery-specific code.
<html>
<body>
Some URL
</body>
</html>
To cancel the navigation operation, simply make sure that the method invoked by the onclick event returns false at the end.
A neat example of the JQuery image popup I described can be found here.
Use ajax if it adds value for the user.
If the ajax version adds a lot more value than the non-ajax version then it might justify the expense to develop a solution that caters for both clients. Generally i wouldn't recommend doing the extra work (remember.. more code results in more maintenance).
I think one point is missing here: Use Ajax only for content any search engine does not need to know.
98% of users will have AJAX enabled browsers.
A significant percentage of those people won't have it turned on when they first visit your site though (or at all, ever perhaps).
I've seen websites that look like a blank page without javascript on. Don't be one of them. Javascript to fix layout issues is a horrible idea in my opinion. Make sure it loads and looks ok without Javascript. If people can atleast see what they are missing out on, they are likely to switch it on, but if your website looks like it's just broken, then...
I often have noscript block Flash and JavaScript until I make the decision that your site is worthy.
So be sure to tell me what I'm missing if I have JavaScript turned off.
It depends on the complexity of your web application.
If you can, having it functional with javascript disabled is great, because it makes your application usable not only by users on js-disabled browsers but also by robots. The day you decide to write an application to automatically fill your forms, for example, you don't have to write an API from the ground up.
In any case, do not user AJAX for EVERYTHING! I have just inherited a project that basically consists of a single page that is populated by a ton of AJAX calls and I can tell that you just thinking about it gives me physical pain. I guess the original developer didn't like the concept of using the back/forward button in the browser as a mean of navigation.
Unless you are targeting mobile devices or other non-standard web users, you can be fairly sure that the vast majority has Javascript enabled, because most major sites (including SO) rely heavily on it.
I want my application to be as accessible as possible.
You can do things like rendering your modals and forms as a page that can operate standalone.
The AJAX version pulls the template into a modal/container, the standalone version checks if it's an AJAX request and renders the page including the header/footer (this can occur from the same URL if planned well)
The AJAX version intercepts the submit and does AJAX submission then provides an inline thank you, the non-AJAX opens a thank you page. Once again you can likely use the same pages for each of these functions if thought out correctly.
Reusing templates and URL's helps avoid additional maintenance for the AJAX/non-AJAX versions.
I want my application to be enhanced by AJAX, but also fully
functional without AJAX.
Thinking through the structure of your URLs and templates can go a long way towards this, if you make most of your AJAX requests pull in completely rendered templates (as opposed to just data) then you can usually use the same URL to serve both versions. You just serve only the guts of the modal/form to the AJAX request and the entire page to a regular request.
When should I not use AJAX?
You should not use AJAX if doing so will cause a poor experience for a significant portion of your user base (there are of course techniques that can be used to mitigate this)
You should not use AJAX if the development time associated with implementing it will be too significant to justify the improvements in user experience
You should not use AJAX for content which has significant SEO value without implementing an appropriate fallback that allows it to be indexed (Crawlers are improving constantly but it's still a good idea)
I mean, should I bother making my application usable without AJAX? Or
does everyone have AJAX enabled browsers these days?
I'd say a lot of the time it's unnecessary as the vast majority of users will have AJAX enabled browsers, but there are scenarios where it's critical such as SEO optimization or when a large portion of your user base is likely to use browsers that are less likely to support Javascript as well or where they're likely to have Javascript/AJAX disabled.
A few examples of these scenarios:
A website for a company or government that uses an outdated browser as standard
A website where a large portion of the users may be disabled in a manner that may negatively impact their experience such as a website for vision or motor-skill impaired people may be negatively impacted by updating content via AJAX especially if it occurs rapidly.
A site accessed regularly via a less common device or browser that will cause a negative impact to a large portion of users
So what should I do?
Think about who is going to be using the site, how they're going to access it, and what they're going to access it with. Also try to think about not just the present but also the future.
Design the site in a manner that will cater to the majority of these users.
Think who will gain and who will loose based on my decision to use AJAX and if in doubt have a look at your analytics data to help weigh up the decision and if you lack the data it may be worth updating your tracking and obtaining a sample to aid the decision
Think does my decision to use AJAX cause any contradictions with core requirements for this project
Use AJAX to enhance content where possible as opposed to making it mandatory ie the content should work with or without JS/AJAX
Consider the additional development time involved with the use of AJAX (if any)
My experience is, we should use ajax after it works without it. For a couple of reasons.
First, if something breaks in the ajax, and you don't have it working without it, the site simply doesn't work. For example, a product list with pagination. It should work with the links alone, then use ajax when possible.
Second, for site indexing and accessibility. If it works without ajax, it's better.
And it's easier to break something (even if only for a few moments). A bad piece of code, an uncaught exception, an external library not loaded, a blocking browser extension,...
After everything works without ajax, its quite easier to add ajax. Just have the ajax catch the action, add ajax=1 and when returning the result, return only what you need if ajax=1, otherwise return everything.
In the product list example, I would only return the products and pagination html, and add to the correct div. If ajax stops working, the whole page is loaded and the customer sees the second page as it loads.
Ajax adds a lot of value to UX. If done right, the user gets a great feel when using the site, and better data usage because it doesn't load the whole page everytime.
But the question being "when not to use ajax", I would say, you should always count on it to improve UX but not rely on it for the site to work (as other users also mentioned). And nowadays we need both, great code and great user experience.
My practice is to use two main pages, let's say index.py and ajax.py. First one is responsible for generating full website, and is default target of forms. Other one generates only output specific for adequate ajax query. Logic behind both of them is the same, only the method of generating output is a bit different.
In jquery I simply change action parameter when sending a request. It works both with and without ajax, although long time have I not seen someone with disabled js and ajax.
I like the thought of coding your application without JavaScript / Ajax and then adding it in later to enhance the UI without depriving users of functionality just because they don't have JavaScript enabled. I read about this in Pro ASP.NET MVC but I think I've seen it elsewhere in reading about unobtrusive JavaScript.
You should not make your service bloated with web 2.0 effects like accordion, modal/etc forms, image zoomers etc.
Use modern tech smarter (AJAX is one of them) and your users will be happy. Do not fear AJAX -- this is very good thing to make user expirience smooth. But don't do things because you like it - do them because your user need it ;)
When you want to make a website that looks like a website, not a fugly imitation of a desktop app?
You should not use AJAX or JavaScript in cases where:
your system needs to be accessible
your system needs to be search friendly
However, by using a modern JS framework with some solid "unobtrusive" practices, you can progressively enhance pages so that they remain accessible and search-friendly while offering a slick UI to users.
This totally depends on the type of application or feature you're developing. If it is crucial that the application is accessible despite the absence of Javascript, then it would help to have fallback methods (i.e. alternative forms) to allow your user to use said functionality/feature. For that, it will require you to invest some of your time developing methods for collecting information not just using client-side scripts but also on the server-side.
For miscellaneous features that only serves to enhance user experience, it's mostly not worth it to develop fallback methods.
There's no reason to totally not use AJAX. AJAX helps minimize your traffic after all.
You can if you wish always use AJAX and update the history state using Push State or for more compatibility use the hash with none HTML5 compliant browsers.
with this you can have your server load a page then javascript read the document.hash and resume the state of the application base on the state of the hash.
for example i got to /index.html i click into something for example a client to open the view client you can change the hash to #/view/client/{client_id}/ then if a reload or go back using the browser the hash with change and you can use the onhashchanged event to capture it and match the sites state to the new hash then same if a favorite a certain state
A couple of other scenarios where one may be better off NOT using AJAX:
Letting someone to log into the web application. Use traditional form submit instead.
Searching and returning more than a few 100 rows from the database. Either break the process down or let the server side language handle it.

Using Javascript to render data onload

This post probably will need some modification. I'll do my best to explain...
Basically, as a tester, I have noticed that sometimes programers who use template-based web back ends push a lot of stuff into onload handlers that then do stuff like load menu items, change display values in forms, etc.
For example, a page that displays your network configuration loads blank (or dummy values) for the IP info, then loads a block of variables in an onload function that sets the values when the page is rendered.
My experience (and gut feeling) is that this is a really bad practice, for a couple reasons.
1- If the page is displayed in an environment where Javascript is off (such as using "Send Page") the page will not display properly in that environment.
2- The HTML page becomes very hard to diagnose, because what is actually on screen is needs to be pieced together by executing the javascript in your head (this problem is less prominent w/ Firefox because of Firebug).
3- Most of the time, this is not being done via a standard practice of feature of the environment. In other words, there isn't a service on the back-end, the back-end code looks just as spaghetti as the resulting HTML.
and, not really a reason, more a correlation:
I have noticed that most coders that do this are generally the coders that have a lot of code-related bugs or critical integration bugs.
So, I'm not saying we shouldn't use javascript, I think what I'm saying is, when you produce a page dynamically, the dynamic behavior should be isolated to the back-end, and you should avoid changing the displayed information after the page is loaded and rendered.
I think what you're saying is what we should be doing is Progressive Enhancement with JavaScript.
Also related: Progressive Enhancement with CSS, Understanding Progressive Enhancement and Test-Driven Progressive Enhancement.
So the actual question is "What are advantages/disadvantages" of javascript content generation?
here's one: a lot of the things designers want are hard in straight html/css, or not fully supported. using Jquery to do zebra-tables with ":odd" for instance. Sometimes the server-side framework doesn't have good ways to accomplish this, so the way to get the cleanest code is actually to split it up like that.

Categories

Resources