Good programmer Web front-end share how to build a single page Web application. First let’s take a look at what a single page application is. The so-called single page application refers to the integration of multiple functions on a page, or even the whole system has only one page, and all the business functions are its sub-modules, which are connected to the main interface in a specific way. It takes AJAX technology to the next level, taking AJAX’s no-refresh mechanism to the extreme, and thus creating a smooth user experience comparable to that of a desktop application.


In fact, we are not unfamiliar with single-page applications. Many people have written ExtJS projects and implemented systems that are naturally single-page, and some people have implemented similar things with jQuery or other frameworks. It is possible to implement a single page application with a variety of JS frameworks, even without frameworks. It is just a concept. There are frameworks suitable for developing such systems, and if you use them, you can get a lot of convenience.


First, development framework


ExtJS can be described as the first generation of single-page application frameworks. It encapsulates various UI components, and users mainly use JavaScript to complete the entire front end, including layout. As ExtJS has grown in size, even for internal systems, let alone systems like these running on the Internet, it can sometimes become cumbersome.


JQuery focuses on DOM operation and its plug-in system is relatively loose. Therefore, compared with ExtJS, it is more suitable for developing a single-page system running on the public network. The whole solution will be relatively lightweight and flexible.


But because jQuery is geared toward upper-level operations, there is no constraint on how your code is organized. How to control the cohesiveness of each module in the case of ballooning code and properly generate data transfer and sharing between modules becomes a challenge.


In order to solve the problem of code logic when the size of a single page application increases, many MV* frameworks have emerged. Their basic idea is to create a module layer and communication mechanism at the JS layer. Some are MVC, some ARE MVP, some are MVVM, and almost all of them have mutated in these patterns to suit the characteristics of front-end development.


These frameworks include Backbone, Knockout, AngularJS, Avalon, etc.


Two, componentization


These on the front end do layered framework to promote the modular code, the so-called componentization, in the traditional Web products, more refers to the UI components, but actually component is a broad concept, traditional Web UI components in the products of high because of its thickness, with the increase of proportion of client code, a considerable part of the business logic and front end, This has led to the emergence of many non-interface components.


One advantage of layering is that the responsibilities of each layer are more specific, so it can be covered by unit tests to ensure quality. One of the biggest headaches with traditional UI layer testing is that the UI layer is mixed with logic, often changing the DOM during callbacks to remote requests. When layering is introduced, these things can be tested separately, and then scenario testing ensures the overall flow.


Code isolation


Compared with the development of traditional page web site, there are some special points worth paying attention to in the process of implementing a single page application.


From the point of view of the characteristics of single-page application, it is more dependent on JavaScript than the page-type website, and because of the single-page page of the page, the JavaScript code of each sub-function gathers in the same scope, so the isolation and modularization of the code become very important.


Page templates are common in single-page applications. Many frameworks come with specific templates built in, while others require the introduction of third-party templates. These templates are interface fragments, and we can think of them as JavaScript modules, which are another type of component.


Templates also have a need for isolation. What are the problems caused by not isolating templates? The conflict between templates mainly exists in the ID attribute. If a template contains a fixed ID, when it is rendered in batches, multiple elements with the same ID will appear in the scope of the same page, resulting in unpredictable consequences. Therefore, we need to avoid using ids in our templates, and if there is a need to access the DOM, it should be done through other selectors. If a single-page application is highly componentized, it is likely that element ids will not be used throughout the application.


4. Code merge and load strategy


People system for a single page load time tolerance is different from the Web page, if they are willing to wait for 3 seconds, for shopping page loading is likely to be willing to pay for a single page of the application of the first loading waiting for 5 to 10 seconds, but after that, the use of various functions should be more smoothly, as far as possible all sub function page to switch success within 1 to 2 seconds, Otherwise they will feel the system is slow.


From the point of these characteristics, we can put more public function to load for the first time, as to reduce the load of each load quantity, there are some sites even put all the interface and logic in the home page is loaded, each time a business interface switch, only produce data request, therefore its response is very quickly, such as wan console is doing just that.


In a single page application, there is no need to load JS after HTML to prevent file loading from blocking rendering, as web products do, because the interface is basically dynamically generated.


When switching functions, in addition to generating data requests, you also need to render the interface. This newly rendered interface widget is usually an interface template. Where does it come from? There are two types of sources, either instant requests, as data is requested via AJAX, or built-in locations in the main interface, such as script tags or invisible Textareas, which have the advantage of speed when switching functions, but burden the main page.


In traditional page-based sites, pages are isolated from each other, so if reusable code exists between pages, it is typically extracted into separate files and may need to be merged according to the needs of each page.


In a single-page application, if the total amount of code is not large, the whole package can be loaded on the home page. If it reaches a certain size, it can be loaded at run time. The granularity of loading can be relatively large, and there is no repeating part between different blocks.


5. Routing and status management


Some of the first online applications we looked at were routing-managed and some were not.


What is the purpose of managing routes? To reduce navigation costs for users. Let’s say we have a feature that takes multiple clicks to navigate through the menu before it shows up.


If a user wants to share this feature address with others, how can he do so?


Traditional page-based products don’t have this problem because they are page-based, and sometimes server-side routing takes care of it.


But in single-page applications, this becomes a problem because we only have one page and the various functional blocks on the interface are dynamically generated. So we want to achieve such a function through the management of the route.


The idea is to divide product functionality into states, map each state to a route, and then use mechanisms like pushState to dynamically resolve the route to match the functionality interface.


With routing, our single-page product can move forward and backward as if it were between pages.


In fact, outside of Web products, there are already technical solutions for managing routing. In AdobeFlex, for example, TabNavigator and even the selected state of the drop-down box are mapped to the url, because it is also a single “page” product model that faces the same problem.


When the product state gets too complex, routing becomes difficult to use because state management is cumbersome, such as the C9.io online IDE we demonstrated at the beginning, which cannot map state to URL.


Caches and local storage


Caching is an important part of the operation mechanism of a single page application.


Since the front end of such a system is almost all static files, it has the opportunity to take advantage of the browser’s caching mechanism. For example, a dynamically loaded interface template can also do some custom caching mechanism to take the cached version directly on the non-first request to speed up the loading.


There are even solutions that cache JavaScript code while loading it dynamically. AddyOsmani’s basket. Js, for example, uses HTML5localStorage to cache JS and CSS files.


In single-page products, business code often needs to deal with localStorage to store some temporary data. You can use localStorage or localStorageDB to simplify your business code.


7. Server communication


Traditional Web products usually use JSONP or AJAX to communicate with the server, but in single-page Web applications, there are a large part of real-time communication such as WebSocket.


WebSocket has significant advantages over traditional HTTP-based communication mechanisms. It makes it easy for the server to use reverse push, where the front end responds only to events that actually produce business data, reducing the need for meaningless AJAX polling over and over again.


Since WebSocket is only supported on more advanced browsers, there are libraries that provide interoperability across browsers, such as socket.io, which demots to AJAX or JSONP in browsers that do not support WebSocket and is completely transparent and compatible with business code.


Eight, memory management


Traditional Web page is generally don’t need to worry about memory management, because the user retention time is relatively less, even if a memory leak, may soon be washed clean by operating a page refresh, but a single page application is different, its users is likely to take it all day, so we need to the DOM manipulation, such as network connection part take care all the more.


Nine, style planning


In single-page applications, style planning becomes important because pages are highly integrated and all pages are aggregated into the same scope.


There are several aspects of style planning:


1. Separation of baseline styles


This includes browser style resets, global font Settings, basic layout conventions, and responsive support.


2. Component style division


There are two levels of planning, the first is the style of various interface components and their child elements, and the second is some decoration style. Component styles should minimize interdependence and allow for redundancy.


3. Management of stack order


Traditional Web pages are characterized by many elements but few layers, so single-page applications can be a little different.


In a single page application, you need to plan ahead for the stacking order of the various UI components, namely the Z-index, for example, we might have various pop-up dialogs, floating layers, and they might combine into various stacked states. The z-index of the new dialog box needs to be higher than the old one to be sure to cover it. And so on, we need to make plans for these possible cover, so, how to plan?


Those who know about communication will know that different frequency segments are divided into different communication modes. In some countries, the use of airspace is also divided. We can also pre-segment in the same way, so that the Z-index of different types of components falls into their respective intervals to avoid conflict between them.


X. Product form of single page application


We mentioned at the beginning that there are many new Web products that are built as one-page applications, but the reality is that these products don’t just exist on the Web. If you go to the Chrome Store, you’ll find a lot of offline apps that can be considered one-page apps.


In addition to various browser plugins, a shell platform like Node-WebKit allows us to use Web technologies to build native applications, and the main part of the product is still the familiar one-page application.


The popularity of single-page applications is gradually increasing. If you pay attention to some Internet start-ups, you will find that a large part of the product model is single-page. This mode provides a smooth user experience and requires a high level of JavaScript skills during the development phase.


In single-page application development, the front and back ends are naturally separated, with API as the boundary between the two sides. The front end acts as the consumer of the service and the back end acts as the provider of the service.


In this mode, the front end drives the servitization of the back end. When the back end is no longer responsible for template rendering and page output, it can focus more on the implementation of the API provided. In this case, the status of the Web front end and various mobile terminals is equal, which gradually makes the back end API no longer need to be designed differently for each end.


Changes in deployment patterns


In this day and age, we can already see the emergence of a product, that is, “back-end free” Web applications. What is it? With that in mind, your product probably just needs to write your own static Web pages, customize the server APIS and cloud storage on some kind of BaaS(Backendaservice) cloud platform, integrate the SDK provided by that platform, interact with it through AJAX, etc., Realize registration and authentication, social contact, message push, real-time communication, cloud storage and other functions.


If we look at this pattern, we can see that the front and back end deployments are completely separated. The front end code is completely static, which means that they can be placed on the CDN and access is greatly accelerated, while the server is hosted on the BaaS cloud and developers don’t have to pay attention to the tedious details of deployment.


Let’s say you’re an entrepreneur working on a real-time, collaborative, one-page product, where you can quickly customize back-end services in the cloud and spend most of your precious time developing the product itself.


12. Disadvantages of single page applications


The fundamental drawback of single-page apps is that they are bad for SEO because most of the interface is dynamically generated, making it difficult for search engines to index.


Xiii. Challenges brought by single-page product


For a product to be one-page, it must first fit into a one-page shape. Secondly, in this process, there will be some changes to the development mode, and there will be some requirements for development skills.


The developer must have good JavaScript skills and an understanding of componentization and design patterns. He is no longer dealing with a simple page, but with desktop software running in a browser environment.