Isomorphic javascript:the Future of Web Apps

Source: Internet
Author: User

Isomorphic javascript:the Future of Web Apps

At Airbnb, we've learned a lot over the past few years while building rich web experiences. We dove into the Single-page app World on our mobile web site, and has since launched Wish Lists and our newly- Redesigned search page, among others. Each of the these are a large JavaScript app, meaning that the bulk of the code runs in the browser in order to support a more Modern, interactive experience.

This approach was commonplace today, and libraries like Backbone.js, Ember.js, and Angular.js has made it easier for devel Opers to build these rich JavaScript apps. We have found, however, which these types of apps have some critical limitations. To explain why, let's first take a quick detour through the Web apps.

JavaScript grows up

Since the dawn of the web, the browsing experience have worked like This:a Web Browser would request a particular page (SA Y, "http://www.geocities.com/"), causing a server somewhere on the Internet to generate an HTML page and send it back The Wire. This have worked well because browsers weren ' t very powerful and HTML pages represented documents that were mostly static a nd self-contained. JavaScript, created to allow Web pages to is more dynamic, didn ' t enable much more than image slideshows and date picker W Idgets.

After years of advances in personal computing, creative technologists has pushed the web to its limits, and web browsers has evolved to keep up. Now, the WEB had matured into a fully-featured application platform, and fast JavaScript runtimes and HTML5 standards had Enabled developers to create the rich apps this before were only possible on native platforms.

The Single-page App

It wasn ' t long before developers started to build out entire applications in the browser using JavaScript, taking Advantag E of these new capabilities. Apps like Gmail, the classic example of the Single-page app, could respond immediately to user interactions, no longer nee Ding to make a round-trip to the server just to render a new page.

Libraries like Backbone.js, Ember.js, and angular.js is often referred to as Client-side MVC (Model-view-controller) or M VVM (Model-view-viewmodel) libraries. The typical client-side MVC architecture looks something like this:

The bulk of the application logic (views, templates, controllers, models, internationalization, etc.) lives in the client, And it talks to a API for data. The server could is written in any language, such as Ruby, Python, or Java, and it mostly handles serving up an initial BA Rebones page of HTML. Once the JavaScript files were downloaded by the browser, they was evaluated and the Client-side app is initialized, Fetchi ng data from the API and rendering the rest of the HTML page.

This was great for the user because once the app was initially loaded, it can support quick navigation between pages without Refreshing the page, and if do right, can even work offline.

This was great for the developer because the idealized Single-page app have a clear separation of concerns between the Clien T and the server, promoting a nice development workflow and preventing the need to share too much logic between the, W Hich is often written in different languages.

Trouble in Paradise

In practice, however, there is a few fatal flaws with this approach the prevent it from the being right to many use cases.

Seo

An application that can only run in the client-side cannot serve HTML to crawlers and so it would have poor SEO by default. Web crawlers function by making a request to a Web server and interpreting the result; But if the server returns a blank page, it's not of much value. There is workarounds, but not without jumping through some hoops.

Performance

By the same tokens, if the server doesn ' t render a full page of HTML but instead waits for Client-side JavaScript Users would experience a few critical seconds of blank page or loading spinner before seeing the content on the page. There is plenty of studies showing the drastic effect a slow site have on users, and thus revenue. Amazon claims that is 100ms reduction in the page load time raises revenue by 1%. Twitter spent a year and engineers rebuilding their site-to-render on the server instead of the client, claiming a 5x i Mprovement in perceived loading time.

Maintainability

While the ideal case can leads to a nice, clean separation of concerns, inevitably some bits of application logic or view L Ogic end up duplicated between client and server, often in different languages. Common examples is date and currency formatting, form validations, and routing logic. This makes maintenance a nightmare, especially for more complex apps.

Some developers, myself included, feel bitten by this approach-it's often only after have invested the time and effort To build a Single-page app, it becomes clear what the drawbacks is.

A Hybrid Approach

At the end of the day, we really want a hybrid of the new and old Approaches:we want to serve fully-formed HTML from the Server for performance and SEO, but we want the speed and flexibility of client-side application logic.

To this end, we've been experimenting at Airbnb with "isomorphic JavaScript" apps, which is JavaScript applications that Can run both on the Client-side and the server-side.

A isomorphic app might look like this, dubbed here "Client-server MVC":

Some of your application and view logic can executed on both the server and the client. This opens to sorts of doors-performance optimizations, better maintainability, Seo-by-default, and more stateful we B Apps.

With node. js, a fast, stable server-side JavaScript runtime, we can now do this dream a reality. By creating the appropriate abstractions, we can write our application logic such this it runs on both the server and the Client-the definition of isomorphic JavaScript.

Isomorphic JavaScript in the Wild

This idea isn ' t New-nodejitsu wrote a great description of the isomorphic JavaScript architecture in 2011-but it ' s been SL ow to adopt. There has been a few isomorphic frameworks to spring up already.

Mojito is the first Open-source isomorphic framework to get any press. It's an advanced, Full-stack node.js-based Framework, but its dependence on YUI and yahoo!-specific quirks haven ' t LEDs to Much popularity in the JavaScript community since they open sourced it in April 2012.

Meteor is probably the most well-known isomorphic project today. Meteor is built from the ground up to support real-time apps, and the team is building a entire ecosystem around its pack Age manager and Deployment Tools. Like Mojito, it's a large, opinionated node. JS Framework, however it ' s done a much better job engaging the JavaScript com Munity, and its much-anticipated 1.0 release is just around the corner. Meteor is a project to keep tabs On-it's got an all-star team, and it's raised $11.2 M from Andreessen horowitz-unhear D of for a company wholly focused in releasing an Open-source product.

Asana, the task management app founded by Facebook cofounder Dustin Moskovitz, have an interesting isomorphic story. Not hurting to funding, considering Moskovitz ' status as youngest billionaire in the world, Asana spent years in R/R Developing their closed-source luna framework, one of the most advanced examples of isomorphic JavaScript around . Luna, originally built on v8cgi in the days before node. JS existed, allows a complete copy of the app to run on The server for every a single user session. It runs a separate server process for each user, executing the same JavaScript application code on the server so is Runn ing in the client, enabling a whole class of advanced optimizations, such as robust offline support and snappy real-time U Pdates.

We launched a isomorphic library of our own earlier the year. Called Rendr, it allows you-to-build a Backbone.js + handlebars.js Single-page app that can also is fully rendered on the Server-side. Rendr is a product of we experience rebuilding the Airbnb mobile web app to drastically improve pageload times, which is Especially important for users on High-latency mobile connections. Rendr strives to is a library rather than a framework, so it solves fewer of the problems for your compared to Mojito or Me Teor, but it's easy to modify and extend.

Abstraction, abstraction, abstraction

That's these projects tend to being large, full-stack Web frameworks speaks to the difficulty of the problem. The client and server is very dissimilar environments, and so we must create a set of abstractions that decouple our APPL Ication logic from the underlying implementations, so we can expose a single API to the application developer.

Routing

We want a single set of routes that map URIs patterns to route handlers. Our route handlers need to being able to access HTTP headers, cookies, and URI information, and specify redirects without dir ectly accessing window.location (browser) or req and res (node. js).

Fetching and persisting data

We want to describe the resources needed to render a particular page or component independently from the fetching Mechanis M. The resource descriptor could is a simple URI pointing to a JSON endpoint, or for larger applications, it could be useful To encapsulate resources in models and collections and specify a model class and primary key, which at some point would g Et translated to a URI.

View rendering

Whether we choose to directly manipulate the DOM, stick with string-based HTML templating, or opt for a UI component Libra Ry with a DOM abstraction, we need to is able to generate markup isomorphically. We should is able to render any view on either the server or the client and dependent on the needs for our application.

Building and Packaging

It turns out writing isomorphic application code was only half the battle. Tools like Grunt and Browserifyare essential parts of the workflow-actually get the app up and running. There can be a number of build steps:compiling templates, including client-side dependencies, applying transforms, Minifi cation, etc. The simple case was to combine all application code, views and templates into a single bundle, but for larger apps, this CA n result in hundreds of kilobytes to download. A more advanced approach are to create the dynamic bundles and introduce asset lazy-loading, however this quickly gets Complica Ted. Static-analysis tools like Esprima can allow ambitious developers to attempt advanced optimization andmetaprogramming to R Educe boilerplate code.

Composing Together Small Modules

Being first to the market with a isomorphic framework means you has to solve all these problems at once. But this leads to large, unwieldy frameworks that is hard to adopt and integrate into an already-existing app. As more developers tackle this problem, we'll see a explosion of small, reusable modules that can be integrated together To build isomorphic apps.

It turns out the most JavaScript modules can already is used isomorphically with little to no modification. For example, popular libraries like underscore, backbone.js, handlebars.js, moment, and even jQuery can is used on the SER Ver.

To demonstrate the this point, I ' ve created a sample app called Isomorphic-tutorial so can check out on GitHub. By combining together a few modules, each of the can be used isomorphically, it's easy-to-create a simple isomorphic app in Just a few hundred lines of code. It uses Director for Server-and browser-based routing, Superagent for HTTP requests, and handlebars.js for templating, AL L built on top of a basic Express.js app. Of course, as an app grows in complexity, one have to introduce more layers of abstraction, but my hope was as more dev Elopers experiment with this, there would be is new libraries and standards to emerge.

The View from here

As more organizations get comfortable running node. js in production, it's inevitable that's more and more web apps would b Egin to share code between their client and server code. It's important to remember that isomorphic JavaScript was a spectrum-it can start with just sharing templates, progress T o Be-an entire application's view layer, all the the-the-the-majority of the app ' s business logic. Exactly what and how JavaScript code was shared between environments depends entirely on the application being built and it s unique set of constraints.

Nicholas C. Zakas have a nice description of how he envisions apps would begin to pull their UI layer down to the server fro M the client, enabling performance and maintainability optimizations. An app doesn ' t has to rip off its backend and replace it with node. js to use isomorphic JavaScript, essentially throwing The baby with the bathwater. Instead, by creating sensible APIs and RESTful resources, the traditional backend can live alongside the node. JS layer.

At Airbnb, we ' ve already begun to retool our client-side build process to use node.js-based tools like Grunt and Browserif Y. Our main Rails app may never is entirely supplanted by a node. js app, but by embracing these tools it gets ever easier To share certain bits of JavaScript and templates between environments.

You heard it's here First-within a few years, it'll be the rare to see a advanced web app that isn ' t running some Javascrip T on the server.

Learn More

If This idea excites you, come check out the isomorphic JavaScript workshop I'll be teaching at Devbeaton Tuesday, Novembe R in San Francisco, or at General Assembly on Thursday, November 21. We ' ll hack together on the sample node. js isomorphic-tutorial app I ' ve created to demonstrate how easy it really are to get Started writing isomorphic apps.

Also keep tabs on the evolution of the Airbnb web apps by following me at @spikebrehm and the Airbnb Engineering team at @ Airbnbnerds.

Isomorphic javascript:the Future of Web Apps

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.