What's the role of Javascript / jQuery / Coffeescript in Ruby on Rails? - javascript

I have been learning Ruby & more specifically the rails framework the past few months and am now preparing to dive into Javascript. I know that any good/modern rails app will include javascript within its code. I also know that Javascript/Jquery/Coffescript help with adding some interactivity, style and functionality to web apps.
My question is what is the standard set of problems/features that one approaches with JS (or Jquery/Coffescript ect) vs Ruby/Rails?

Use Rails to:
Build Extensible applications with MVC (Model, View, Controller) code.
Manage Data (CRUD - Create, Read, Update, Delete).
Manage Security (Access) and Authentication (Identity).
Manage State over time.
Apply REST for standard actions.
Apply a 'middle layer' for validations (the database being the backend validator).
Manage the back end part of AJAX communication and processing.
Build applications in a TDD/BDD Agile fashion with code that is easy to understand.
Build API's for communication.
Provide a full-stack Application Server.
Use Javascript and libraries like jQuery for:
Improved user interaction - Sliders, highlights, glows, color changes, etc.
Improved user feedback - the 'front line' for immediate feedback for validations.
Improved page load speed - less page loads and fewer user experience interrupts.
Improved User experience with effects. - Transitions, Fades, etc.
Presenting and Managing interactive contents e.g. maps, video, sounds.
Tasks that are specific to managing the DOM - HTML, CSS and browser events.
The front end part of communication via AJAX.
Making things look & work similarly in different browsers & browser versions.
Pre-built tools for sliders, image fades, forms, layouts, tool tips, etc.
Pre-built mini-apps, ready to apply to any data. Isotope is one amazing example!

Some tasks you would do with javascript:
update parts of a web page without the user having to reload the whole page.
3rd party sources eg - I had google map on a site and used almost all javascript for it.
pop-ups, user interaction
display videos, interactive images.
Some tasks you would do with ruby/rails:
all your server side stuff like get data from your models.
make sense of any data your client sends to your application.
process your data before sending it to the browser.

Javascript is client side and can manipulate the page after it has loaded. Its more about interaction with the page while rails is the backend of a app. Javascript is present in most web sites, ruby/rails or not.

Related

MVC5 vs Angular JS

I've been working with ASP.NET MVC for about a year now. I enjoy the ability to create SPA's especially by using the following tools:
Partial views(via html.action() and renderPartial())
Ajax helpers (Ajax.Actionlink() and Ajax.beginform())
My question is, Is it safe to just continue without a JavaScript frameworks or am i seriously missing out on something by not utilising a Javascript framework like Angular JS.
This depends a lot of the type of application you are building, but in general you don't necessarily have to choose between ASP.NET MVC and Angular, you can use both in a project.
For example, if you have a page with a grid where the user will add rows and you have to calculate sums etc you could use angular on that page (and it will speed up the development process).
But if you have pages with static content you can just serve an html file there using ASP.NET MVC.
And you can even use both of them. For something like a blog post, you can use a static html file for the post content and then implement the comments are with angular.
Since ASP.NET is a server side framework, it can only go that far as AJAX insertions. Angular JS is a client side Framework, designed for SPA in mind. If you are going for a light SPA, ASP.NET will do nicely, but I think you should use the right tools for the right job. Don't hesitate to mix them in order to find the right place between server side rendering and client side dynamism.
You are definitely missing some things.
The purpose of frameworks such as angular is not just to handle your bootstrap tab switches or whatever to display just parts of the UI rather than everything. Sure, you can create small and simple SPAs by utilizing such logic but once you come to create real-world apps that approach will become unusable. The reasons to this are:
Your site will be highly unmaintainable
Frameworks like angular provide much more than just templating (more on that in a moment) but features such as routing, which allows on-demand content loading. That is, instead of sending the whole page to the client, much of which (s)he maybe will not even take a look at, you can load fragments of HTML on-demand, which reduces network usage. Imagine you had to download everything (posts, images, videos, chat messages etc) on Facebook and hide them until you actually want to see them.
Back to templating, this is a very powerful feature. Again, in the case of simple apps you can use custom JS code - that is, concatenate strings to create fragments of HTML and then insert them into the DOM. But even with simple apps this is a smelly thing to do. Imagine you had to write custom JS to concatenate your chat messages in an app like Facebook then insert them into the DOM. With angular2, for example, you can do something like this:
<ul>
<li *ngFor="let msg of messages">{{msg.Sender}} said: {{msg.Content}}</li>
</ul>
This way, Angular2 will do all the parsing and DOM handling for you. That is, you write declarative markup rather than imperative logic for what you want to display.
All in all, they help you to decouple the logic from the UI so you should definitely dig into any of the popular frameworks and get a taste of their capabilities if you want to create rich apps. You will not regret it.

PHP template system vs javascript AJAX template

My PHP template looks like this:
$html=file_get_contents("/path/to/file.html");
$replace=array(
"{title}"=>"Title of my webpage",
"{other}"=>"Other information",
...
);
foreach(replace AS $search=>$replace){
$html=str_replace($search,$replace,$html);
}
echo $html;
I am considering switching to a javascript/ajax template system. The AJAX will fetch the $replace array in JSON format and then I'll use javascript to replace the HTML.
The page would then be a plain .html file and a loading screen would be shown until the ajax was complete.
Is there any real advantages to this or is the transition a waste of time?
A few of the reasons I think this will be beneficial:
Page will still load even if the Mysql or PHP services are down. If the ajax fails I can handle it with an error message.
Bot traffic (and anything else that doesnt run JS) will cause very little load to my server since the ajax will never be sent.
Please let me know what your thoughts are.
My 2cents is it is better to do the logic on the template side (javascript). If you have a high traffic site you can off load some of the processing to each computer calling the site. Maybe less servers.
With Javascript frameworks like AngularJs the template stuff is pretty simple and efficient. And the framework will do caching for you.
Yes, SEO can be an issue with certain sites. There at proxy tools you can put in place that will render the site and return the static html to the bot. Plus I think some bots render javascript these days.
Lastly, I like to template on the front-end because I like the backend to be a generic data provider (RESTful API). This way I can build a generic backend that drives web / mobile and other platforms in a generic way. The UI logic can be its separate thing in javascript.
But it comes down to the design needs of your application. I build lots of Software as a service applications so a single page application works well for me.
I've worked with similar design pattern in other projects. There are several ways to do this and the task would involve managing multiple project or application modules. I am assume you are working with a team of developers and not using either PHP or JavaScript MVC framework.
PHP Template
For many reasons, I'm against using “search and replace” method especially using server-side scripting language to parse HTML documents as a templating kit.
Why?
As you maintain business rules and project becomes larger, you will
find yourself reading through a long list of regular expressions,
parse HTML into DOM, and/or complicated algorithms for searching
nodes to replace with correct text(s).
If you had a placeholder, such as {title}, that would help the
script to have fewer search and replace expressions but the design
pattern could lead to messy sharing with multiple developers.
It is ok to parse one or two HTML files to manage the output but not
the entire template. The network response could be slower with
multiple and repetitive trips to server and that's just only for
template. There could be other scripts that is also making trips to
the server for different reason unrelated to template.
AJAX/JavaScript
Initially, AJAX with JavaScript might sound like a neat idea but I'm still not convinced.
Why?
You can't assume web browser is JavaScript-enabled in every mobile
or desktop. You might need to structure the HTML template in few
ways to manage the output for non-JavaScript browsers. You might
need to include <noscript> and/or <iframe> tags on every page. And,
managing alternative template for non-JavaScript browser can be
tedious.
Every web browser interpret JavaScript differently. Most developers
should know few differences between IE, FireFox, Chrome, Safari, and
to name few. You might need to create multiple JavaScript files to
detect then load JavaScript for that specific web browser. You
update one feature, you have to update script for all web browsers.
JavaScript is visible in page source. I wouldn't want to display
confidential JavaScript functions that might include credentials,
leak sensitive data about web services, and/or SQL queries. The idea
is to secure your page as much as possible.
I'm not saying both are impossible. You could still do either PHP or JavaScript for templating.
However, my “ideal” web structure should consist of a reliable MVC like Zend, Spring, or Magnolia. Those MVC framework include many useful features such as web services, data mapping, and templating kits. Granted, it's difficult for beginners with configuration requirements to integrate MVC into your project. But in the end, you could delegate tasks in configurations, MVC concepts, custom SQL queries, and test cases to developers. That's my two cents.
I think the most important aspects you forgot are:
SEO : What about search engine bots ? They wont be able to index your content if it is set by javascript only.
Execution and Network Latency : When your service is working, the browser will wait until the page is loaded (let's say 800ms) before making the extra Ajax calls to get your values. This might add an extra 500ms to get it (depending on network speed and geographic location...). If you have sent all the generated data by your server, you would have spent only ~1ms more to prepare the complete response. You would have a lot of waiting on a blank page.
Caching : You could cache the generated pages on your web app. That way your load will be minimized as well. And also, if you still want to deliver content while your backend services (MySQL/PHP..) are down you could even use Apache or Nginx caching.
But I guess it really depends on what you want to do.
For fast and simple pages, which seems to be your case, stick with backend enhancements.
For a dynamic/interactive app which can afford loading times, and doesn't care about SEO, you can delegate most things to the front-end. But then use an advanced framework like Angular, to handle templating, caching, etc...

responsive HTML5 application [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I have been searching about few details of HTML5 application but finding it hard or may be i am not searching in the right way. Basically i want to understand the new way of creating an application using HTML5 and CSS3 which will provide an experience of native application. Followings are my doubt.
How to navigate page by page. In typical web application every page is requested to the server and server will load the new page in browser with a refresh. In modern approch what is the way to do page navigation without page refresh effect.
In a typical web application a dynamic web programming such as asp.net, JSP are used to generate HTML files in browser. What is the modern approch do we still need to use the same way or plain static HTML files can be used and can be modified by jquery.
How the client server communication has to done so that page refresh does not happens. Can we use jquery for all the communication. Will it too much work for browsers.
How the HTML5 files are hosted. In server or each client has to have a copy of HTML files locally.
Any resources explaining this would be great.
The question is very generic, but I will attempt to answer it.
1. HTML5 is just a new version of HTML which is still under draft according to w3.org. HTML5 is still HTML and HTML navigates to other pages by requesting a fresh copy of the next page from the server, which the server actively responds. This will however flush the existing page from the browser and the new page is brought in. ( And yeah when the same page is requested again, either a cached copy in the browser is displayed or a new request is sent to the server and all the contents,tiny or huge, are reloaded). This is the reload part. However, you can use asynchronous services that AJAX has to offer using which you can request part of a html page.
Ajax is a group of interrelated web development techniques used
on the client-side to create asynchronous web applications. With Ajax,
web applications can send data to, and retrieve data from, a server
asynchronously (in the background) without interfering with the
display and behavior of the existing page.
2. Static pages are rarely used these days. However, if the site does not have too many user specific components or if the site only has static data to put in, then static pages are helpful, because loading the javascript stuff can be avoided. But then again, all modern web pages are dynamic.
There are a lots of ways of putting dynamic content on the web like
the Model View Controller approach and Event Based approaches.
And just to give you an idea, the new look is the one page look where all the content in the site is displayed in one single page and there are multiple controllers that feed various parts of the page and all of it is combined into a view.
Have a look here .
3. There are a lot of new js options these days with node.js and angular.js being the latest additions. Node.js is an excellent option if you want your site completely powered on javascript, however not many hosting sites support node.js yet. However, right now javascript seems to be the future.
4. This question is huge one, owing to the sheer lack of research from your point. Because, hosting and having copies are two different things because other than the hosting site and your client(that is the browser) there are lot of other servers which are put reasonably close to the client to serve pages on the fly, so that the file is brought quickly to the browser.
So, in a sense a lot of websites which have huge number of hits have
layers of fast cached servers upon slow back-end servers to serve
requests quickly. Then there are also fast cached database servers
upon huge slower ones.
So, what I want to stress here is that this is a purely performance related decision that YOU have to take. So, if there is something you want to achieve, whether it be speed or anything else, there are a lot of options to explore.
Coming to the CSS3 part, animations part of CSS3 is still to be accepted globally. There are still users all over the world who have browsers unable to process CSS3D transitions( users using older versions of IE etc). So thats about it.
That said, these things are purely related to performance and HTML5 or CSS3 for that matter have no part to play here.
Check out jQuery Mobile!
Basically jqm and other web mobile frameworks use Ajax to avoid any page refresh, with nice animations as a bonus.
This is more of a matter of how you want to pull data into your web app, from a server? then yes, it's gonna be an ajax request, and yes you will have to insert that into your html page, but again this doesn't mean your whole page has to come from a server. You can basically have a three tier setup, server, middleman, and your frontend. your middle part will have your html templates for your "pages" and will insert the incoming data from the server, and your front end will process and make everything happen. it can be like a php/angular or jquery setup, or php/handlebars/jquery or javascript setup, there are many others. Your page navigation again depends sort of on your framework setup.
Again kinda like the above. Routing is the most common way of communicating to a server these days. YOu basically requests data through different routes to the server and then process the incoming data -json perhaps- in whatever template engine you want to present to your end user. For routing, php solutions are the most popular, like slim or symfony.
Jquery is totally fine, angular is said to be much faster these days. Handlebars is excellent for creating template pages. Angular combines, qjuery, handlebars and some other stuff all in one. Backbone.js another good one.
THis is an odd question or tells me that you need to research some more about the whole concept. But think of in terms of frameworks and MVC type models.
I understand you require a single page HTML 5 app, For page navigations you can use Jquery mobile.It implements it via ajax.If you require the experience of native application.(In mobile devices JQM can be a little slow)You would require to make some performance improvements in jquery mobile, like removing unused widgets,unused themes,using clever javascript for minimal page reflow etc.
For such apps,for code maintainability we require the use of javascript frameworks like backbone js,knockout js etc(You have a wide variety of MVVM frameworks to choose from).
For client server communication you can make AJAX calls.

When is using Angular (or a similar JS MV* framework) with Rails a good idea?

I've been developing a Rails app with a fairly straight-forward UI. When a user logs in, it lists a bunch of items created by the user. Each item has a couple actions. There is also a form to create new items.
I was originally using only the standard Rails templating system and Rails AJAX calls for actions (setting :remote => true, writing response JS, etc), but I recently decided to switch to AngularJS in order to make it easier to implement AJAX actions that directly update the DOM. On the server side, I did away with most of the Rails controllers and moved the actions into a Grape API.
The development process has gotten (slightly) easier, since there is less JavaScript to write, but the performance of the page has suffered. Now, after a page loads, an additional API call must be made in order to populate the page with data. The data is sent to the client as a fairly lengthy JSON string (even though I am gzipping it) and the client must do a lot of work to parse through it and render it all. As a result, the page takes about twice as long to load as it did before.
How can this be overcome, and in general, when does it make sense to use something like Angular in a web app that has a lot of data and is not necessarily a single-page app? It seems like the tradeoff is between having the server do more work and the performance be better in exchange for spaghetti code on the client-side, or having the client do more work and the performance drop in exchange for more beautiful, well-structured code on the client-side.
Is there some happy medium between the two? Would love to hear your thoughts....

Mobile Webapp: render data list in PHP or Javascript?

I am currently developing a webapp aimed for mobile devices which basically consists of a couple of long and complex lists, lots of data, collapsible cascading elements.
I'm getting the data to be displayed as XML, now as I see it I have two options:
build the list on the server and send HTML to the client
send XML to the client, build the list with Javascript/jQuery
Not sure which is more efficient, less data to transfer is good, less load on (especially older) phones is also good.
Any other pros/cons I'm not seeing? Suggestions?
The less data you send the better.
I often prefer to make a one-page application. All of the data needed is loaded via AJAX or Web Sockets (check out Socket.IO for a nice wrapper, with compatibility for mobile browsers that don't directly support Web Sockets). That way, you can have a much smoother user experience, and save bandwidth while doing it.
The con with this method is SEO. Search engines won't be running your JavaScript, and therefore won't index any data you are displaying. For "application" like sites, this is typically not a problem. If your site is more content based, then it might be an issue for you. There are ways around this, and progressive enhancement goes a long way to helping the problem. You will need to decide if this is right for you and your situation.
The presentation of Nicholas C. Zakas on velocity 2013 can help you.
Enough with the JavaScript Already. The peroformace or js rendering is very bad, especially for mobile webapp. We have changed the render of data list form js to php in some appliction. You should try to compare the performace or these two ways, and choose the better one. I recommend you do the render of big list in php, just for performce.

Categories

Resources