Is it okay to write HTML code in JavaScript? - javascript

I wanted to create a Single page App without using front-end frameworks, since it was a small project.
So when user clicks on navigation, it fires an AJAX call and appends (HTML code with formatted data) it to HTML.
This is how it looks: https://gist.github.com/yask123/c786f49c7118e4cd91eab5c56f69257d
Is it super bad practice to do so ? Or should I use Handlebar.js just for this? (Would it be an overkill just for one thing ..? )
Live app: http://dtumart.com/

It is okay to write code in your logic (JavaScript).
Loading an entire framework/library for a single action is usually overkill and there can be several benefits to creating your code in the logic.
The only real concern here is if your JavaScript fails, or the clients browser doesn't support, then the client won't see anything.

Related

Javascript Single Page MVC from scratch

I just wondering what is the technique of creating a single page website by using javascript without using framework like ember js / angular js.
For example in php like they can get
example.com?view=homepage
Can easily get the view and load/display homepage and load homepage's content.
What if in javascript if want to load another page/content?Any technique for building it?
I just building with a simple function like
$("#otherpage").hide();
$("#homepage").show();
I don't know is it the best way to develop a javascript single website page with this way?Or any technique that you all can suggest, cause I need learn from basic, need use javascript to explore and create a single app page without php.
Thanks lot
If it was that easy, do you really think Ember, Spine and Angular would be that widely used?
Snarky comment aside, building a page that refreshes like what you've done, while simple and rather easy to modify, falls very short on quite a few things:
For sites larger than a couple of pages, your HTML markup will become MASSIVE. Not just that, but you'll have to run every single piece of code on every page...per page. Say hi to insane overhead, both on bandwidth and on server-side processing, even with caching.
If you want to dynamically update part of a page, you'll need to use AJAX anyway. Why would it suck to write stuff using an MVC approach from the get-go, rendering data as you go along with AJAX, rather than brute-feeding the entire DOM?
What is the problem with Angular, anyway? Widely used, bug-free, unit-tested, built by reliable people, and if a bug does go through, you can be sure that the community will fix it quicker than you could
If the last comment didn't dissuade you from building your own to replace an already-existing platform, I would strongly recommend you build your JS to be fed data (JSON or otherwise) from your server and to dynamically update the page. You might not want the full-blown MVC approach, but at least the MV part of it. This will also allow modularity.

How to use backbone.js to make a site also functional with client without JS

Take a look at http://www.usatoday.com, the website is made with backbone.js but work perfectly without.
I don't think they use somethings like http://phantomjs.org.
Someone know how they did that?
Thanks
P.S. I also send a mail to usatoday, if they answer and give me the permission I will report her what they say.
They use a technique called progressive enhancement.
Essentially, this means you write the basic site without JS, and only add JavaScript on top of it later to improve the functionality.
There is nothing particularly special to it - the server simply sends the full HTML for the page which can be used to render the site instead of using Backbone to generate the markup on the fly from templates.
To be more specific about the techniques used in this case, it looks like they are generating the content mostly on the server even when using Ajax to load it.
When changing pages with JS enabled, they send the full page content markup from the server. Most likely this is done so that they can improve code reuse between the JS and non-JS versions of the site.
The HTML-block that is sent seems to contain some JSON. Most likely this is loaded for their client-side implementation so it knows what content you are currently viewing.

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.

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