Engineering a better solution than getting a whole HTML document with AJAX - javascript

I have a webpage that I am working on for a personal project to learn about javascript and web development. The page consists of a menu bar and some content. My idea is, when a link is clicked, to change the content of the page via AJAX, such that I:
fetch some new content from a different page,
swap out the old content with the new,
animate the content change with some pretty javascript visual effects.
I figure that this is a little more efficient than getting a whole document with a standard HTTP GET request, since the browser won't have to fetch the style sheets and scripts sourced in the <head> tag of the document. I should also add that I am fetching content solely from documents that are served by my web app that I have created and whose content I am fully aware of.
Anyway, I came across this answer on an SO question recently, and it got me wondering about the ideal way to engineer a solution that fits the requirements I have given for the web page. The way I see it, there are two solutions, neither of which seem ideal:
Configure the back-end (server) from which I am fetching such that it will return content and not the entire page if asked for only content, and then load that content in with AJAX (my current solution), or
Get the entire document with AJAX and then use a script to extract the content and load it into the page.
It seems to me that neither solution is not quite right. For 1, it seems that I am splitting logic across two different places: The server has to be configured to serve content if asked for content and the the javascript has to know how to ask for content. For 2, it seems that this is an inappropriate use of AJAX (according to the previously mentioned SO answer), given that I am asking for a whole page and then parsing it, when AJAX is meant to fetch small bits and pieces of information rather than whole documents.
So I am asking: which of these two solutions is better from an engineering perspective? Is there another solution which would be better than either of these two options?

animate the content change with some pretty javascript visual effects.
Please don't. Anyway, you seem to be looking for a JS MVC framework like Knockout.
Using such a framework, you can let the server return models, represented in JSON or XML, which a little piece of JS transforms into HTML, using various ways of templating and annotations.
So instead of doing the model-to-HTML translation serverside and send a chunk of HTML to the browser, you just return a list of business objects (say, Addresses) in a way the browser (or rather JS) understands and let Knockout bind that to a grid view, input elements and so on.

Related

Should Javascript be used to modify HTML?

I just recently started learning javascript and have a question regarding the'proper use'. I'm still trying to identify the role of Javascript within a website, and I'm curious whether or not it would be considered ok to have Javascript modified the HTML of a web page.
Let's say I have a panel on a web page. This panel houses a list. I would like users to be prompted to add items to this list.
I was thinking that it would be possible to use Javascript to generate list items to add to the list. However, this would be modifying the actual number of HTML elements on the web page... For some reason, this just seems 'hacky'. When I think of HTML, I think of a static structure that should come to life with CSS and Javascript.
So my question: is it considered okay to have Javascript modify the HTML of a web page? What about the case of adding items to a list?
Thank you!
Javascript is a programming language designed so it can modify the document that is being displayed(the DOM), the actual HTML is never touched.
Javascript has a place on a website and modifying the document/dom is perfectly acceptable and without it, would make javascript almost useless. CSS is great for certain tasks, but you can't do everything in CSS, though CSS5 is coming pretty close for many tasks.
Rewriting the entire DOM IS bad practice, but using it to shift an element's position based on an action, or creating a popup overlay is perfectly acceptable.
Remember the gold rule:
Modify as little as possible to accomplish the goal.
What matters is the user's experience of the (HTML) document. The representation of "the document" can change by utilising a language like javascript that "manipulates the DOM" - and the DOM is like an instance of the HTML document, or "document session" if you will.
So in a way, no, the HTML is touched. It is positively manhandled by javascript - indirectly and in a non-persistent way. But if you want to be pedantic... we say it isn't and leave half the readers confused.
When to use javascript and when not to. It's swings and roundabouts. You need to learn (mostly from experience) when one particular tool suits the situation. It usually boils down to some core considerations:
HTML is for markup. Structure. Meaning.
CSS is for style, feel, appearance.
Javascript is for those situations where none of the above work.
And I'm neglecting to mention server-side processing with the obvious disclaimer that all processing that ought to be done in privacy is done on the server (with a programming language like PHP or Ruby for example).
Sometimes you get the grey area in-between where you can do something either way. Those situations you may ask yourself a question like... would it be processed quicker if the client (user's computer) processes it, or the server... and that's where experience comes in.
It depends on the case to decide if you should manipulate DOM directly or let the JS do it.
If you have a static html page, just do your html and hand craft the
DOM. There is no need for JS to get a hand here.
If you have a semi static html page where the user actions change
part of it - then get the JS to do the changing part.
If you have a highly dynamic html page (like single page app) - you
should get the JS to render html mostly.
Using plain JS however is not the best for you in this age of great JS evolution. Learn it -but also learn to use good libraries and frameworks which can take you to the track very fast.
I recommend you to learn Jquery and Angular 2 which make you feel like learning a super set of JS straightaway.
Short disclamer: Javascript may modify DOM content in a browser but never change original HTML served from Web server.
Modern Web is unthinkable without javascript. JS allows to make static HTML interactive and improve User Experience (UX). As any sharp tool JS can produce a masterpiece out of nearly dead page and cut throat to a blooming static content.
Everything is up to the developer.
When not to use JS
Do not use JS to deliver ever-green content to the page. Web bots (crawlers) don't run JS, and you message "I come to this world to testify to the truth" may appear "a voice of crying out of desert" and be non-indexed and thus unread.
When JS in the must
Every time your page visitor does something the page should respond with proper action (using JS or, if possible, just CSS).
This is especially important when a prospect fills in a form. To err is human so a developer via JS should help the visitor to make wrong things right. In many cases it is possible without requesting server and in even more cases the answer should come from the server. And JS is your best friend in this case.
Javascript never lives alone. Browser object is its trustful ally. Most modern browsers support XMLHttpObject A.K.A AJAX (you may remember this name from ancient Greek history) which communicates with the server without reloading the page.
The idea of AJAX which stands for Asynchronous Javascript And Xml is to send request and receive response from the server asynchronously without blocking page in the browser.
Native javascript may be difficult to understand to many beginner developers. To make thing easier there are a lot of JS libraries with jQuery being most known.
Returning to the OP's question, Should Javascript be used to modify HTML?
The answer is: It Depends.

Load HTML with Ajax vs. load only data with Ajax and build the html with Javascript

I'm working on a project which needs to load via AJAX some HTML information on the page.But I'm not quite sure how to load that information.
I don't know which method is better for me:
1) Load the entire HTML with AJAX and then just append it to the page
or
2) Load only the data with AJAX and then build the HTML using Javascript(+JQuery)
The one I tend to use is the first method because it's the easiest one but also it is more expensive regarding the memory (the biggest file I have to load has about 7kb which is not too much)
The second one which is the hardest, involves a huge Javascript (Jquery) code to build the HTML(I have also to load the attributes for the element).And because I have lots of different HTML code to load I have to make lots of conditions (e.g. one for a button, one for a title, one for a textarea etc) and also I have to create variables that containes that HTML.
My question is what method is the best to use in my case?
I would always stick to the solution where I cleanly divide data/logic and view. This would probably the case in the first alternative. Making changes to HTML generated with JavaScript is quite hard.
I'd suggest another option: Use client side templates. Load the template and the data with an ajax call and then fill out the template using javascript. There are some libraries out there for this scenario.
I can imagine a couple of developers working: A full-time back-end developer and a full-time front-end developer.
The BE developer has to send some data for the FE developer to display it right. Thinking of programming as easy as possible, he chooses the first method described by the OP. Everyone is happy.
A few months later, the presentation of this very data needs to be updated. The manager quickly calls the Front-End developer, which says:
"Uhhh... No can do. The entire data already comes formatted directly from the server."
Oh noes! Would this have happened if the data came only as RAW DATA from the server? I wonder =)
the second method:
Load only the data with AJAX and then build the HTML using Javascript(+JQuery)
is much appropriate, one main advantages of these method is your ajax response will become faster.
Also, it is more logical to separate the logic from design.
Note: always the best solution is depend on your specific case.

UI Development - JavaScript vs Ajax

This is a design question. I find myself going back and forth between two UI design styles.
The UI on a prototype I developed recently relied heavily on loading the elements of the UI as partial views via AJAX. I did not like that approach because I had to do a lot of requests to the server while my page was loading. However, the plus of this design was that I could easily edit the partial view templates, so the code was easier to manage.
In the next iteration I decided to package all the information at once and then use JavaScript to generate partial views and plug this information into it (and only use Ajax when on-demand up-to-date information was actually needed). My page loads faster, but I find myself generating a lot of HTML snippets in JavaScript, which is getting harder to manage.
As I see it, using Ajax you get:
Easier to maintain (+)
Longer UI response times (-)
And with JavaScript only, you get
Faster UI response (+)
Easier to handle server-side errors (+)
Harder to maintain (-)
So, There are a few things on which I would like to hear your comments:
I do not like using Ajax unless I don't have a need for actual on-demand data. Am I wrong?
Are there frameworks/libraries that would make managing HTML-generating JavaScript code easier?
Are there any other pros/cons of the two approaches that I have missed?
Thanks,
There are templating libraries for JavaScript, if you want to get that involved. In general I would avoid manually sticking together HTML strings from JS unless there's a particular need to (eg in some cases for performance when dealing with very large tables).
HTML-hacking is difficult to read and prone to HTML-injection security holes when you don't get escaping right.
Start instead with the DOM methods, and use DOM-like content manipulation libraries to make it easier. For example, if using jQuery, do this:
$('<a>', {href: somelink, text: sometext})
and not this:
$(''+sometext+'') // insecure mess
There doesn't need to be a big difference between fetching data through XMLHttpRequest vs including it in the HTML document itself. You can direct a bunch of JSON data to the same function that will build page parts whether it was just fetched by XMLHttpRequest in an update operation, or included in function calls at document load time.
When including data in the page you will generally need to include a timestamp they were generated in any case, so that if the browser goes back to the page a while later without reloading it, the browser can detect that the information is now out-of-date, and cue up an XMLHttpRequest to update it.
The usual question when you're creating your page content from data with client-side JavaScript is, are you going to fill in the initial static HTML version from the server too? If so, you're going to be duplicating a lot of your content generation work in both client-side JS and the server-side language(*). If not, then you're making the content invisible to non-JS user agents which includes search engines. Whether or not that matters to you typically depends on what the app is doing (ie does it need to be searchable and accessible?)
(*: unless you can use server-side JavaScript from something like node.js and re-use your content generation code. This is still a somewhat rare approach.)
Why not look at integrating require.js into your workflow? I'm not entirely sure how it would work with templates, but included in their pipeline is the ability to package all required script files into a single .js to be served by a single server request/response.
I have no personal experience about it, but Closure looks promising. The thing about its templates being usable on both server and client side might be of interest to you. Here is what was said about using it in Google+:
The cool thing about Closure templates is they can be compiled into both Java and JavaScript. So we use Java server-side to turn the templates into HTML, but we can also do the same in JavaScript client-side for dynamic rendering. For instance, if you type in a profile page URL directly, we'll render it server-side, but if you go to the stream say and navigate to someone's profile page, we do it with AJAX and render it client-side using the same exact template.
When working with remote data after a page is loaded, for small datasets I prefer returning data only and adding to the UI with templates.
For large datasets, I recommend using your partial views to render the html on the server to reduce overhead in the client as #bobince mentioned.
For client-side state tracking, check out Knockout at http://www.knockoutjs.com. It uses an MVVM approach with data models bound to UI elements and makes it very simple to send the data back to the server via AJAX. It works with the jquery.tmpl template library out of the box or you can integrate another library of preference with a little more effort.
As far as managing templates, it's easy enough to store common templates in an object, either on the server to be retrieved with your remote data, or in a javascript object on the client.

WebApp that communicates using only json objects?

Hey everyone, I've been thinking about how the majority of web apps works at the moment. If as an example the backend is written in java/php/python what you probably see is that the backend is "echoing / printing" the html ready to the browser, right.
For web apps that works using almost exclusively ajax, is there a reason to not simply communicate without html, as an example just by using JSON objects passing back and fourth between the server and client, and instead of "printing or echoing" html in our script/app backend we simply echo the json string, ajax fetches it and converts the JSON string to an object with all of our attributes/arrays and so on.
Surely this way we have less characters to send, no html tags and so on, and on the client side we simply use frameworks such as jQuery etc and create/format our html there instead of printing and echoing the html in the server scripts?
Perhaps people already do this but I have not really seen a lot of apps work this way?
The reason is that I want todo this is because I would like to separate the layer of presentation and logic more than it currently is, so instead of "echoing" html in my java/php I just "echo" json objects, and javascript takes care of the whole presentation layer, is there something fundamentally wrong with this, what are your opinions?
Thanks again Stackoverflow.
There are quite a few apps that work this way (simply communicating via AJAX using JSON objects rather than sending markup).
I've worked on a few and it has its advantages.
In some cases though (like when working with large result sets) it makes more sense to render the markup on the server side and send it to the browser. That way, you're not relying on JavaScript/DOM Manipulation to create a large document (which, depending on the browser, would perform poorly).
This is a very sensible approach, and is actually used in some of our applications in production.
The main weakness of the approach is that it increases the load on the browser resource-wise and therefore might - in light of browsers often already-sluggish JS performance - lead to worse user experience unless the presentation layer mechanics is very well tuned.
Now a days many webapps use this approach like gmail and other big apps even facebook this
the main advantage of this approach is user dont need to refresh all the pages and he gets what we want to show him or what he desired.
but we have to make a both version like ajax and normal page refresh what if the user refresh the page.
we can use jquery template which generates html and also google's closer which is used by a gmail and other google products.

Including HTML fragments in a page - methods?

This is an extension of an earlier questions I asked, here:
Django - Parse XML, output as HTML fragments for iFrame?
Basically, we're looking at integrating various HTML fragments into a page. We have an small web app generating little fragments for different results/gadgets, at various URLs. This is not necessairly on the same domain as the main page.
I was wondering what's the best way of including these into the main page? We also need the ability to skin the HTML fragments using CSS from the main page.
My initial thought was iFrames, however, I'm thinking the performance of this might not be great, and there's restrictions on CSS/JS manipulation of the included fragments.
Are SSI a better idea? Or should we use php includes? or JS? Any other suggestions? The two main considerations are performance of the main page, and the ability to style/manipulate the included fragments.
Cheers,
Victor
This sounds similar to what Facebook Platform applications do. One kind simply uses IFRAMEs, the other takes output from a backend and transforms it -- <fb:whatever> elements are expanded, JavaScript executed, and things like buttons are skinned. You could look at them for an example.
Using IFRAMEs would probably make things complicated. By default you cannot modify styles inside them from the outer frames, but you could probably use something like Google Closure's net.IframeIo to work around that.
I would try loading widgets using cross-domain scripting. Then you can add the widget's content to the page, however you wish, such as inserting it into the DOM.
iFrames should not be a problem performance-wise - It won't make a difference whether it's the browser doing the querying our your server. You may get design problems though.
SSI and PHP are more or less the same, but they both have the same problem: If the source page is down, rendering of the whole page is delayed.
The best thing performance-wise would be a cached PHP solution that reads the snippet, and is thus less vulnerable towards outages.
Funnily enough, I have written a PHP-based tool for exactly this purpose, and the company I wrote it for has agreed on publishing it as Open Source. It will be at least another four weeks, though, until I will get around to packaging it and setting up the documentation. Should that be of any interest to you despite the timeframne let me know and I will keep you updated.

Categories