The current web application development is basically centered on rich Internet applications (RIA. There are many Ria implementation technologies: Ajax, Flash, javafx, and sliverlight. The advantage of Ajax technology is that it is built on open standards, and there is no vendor lock problem, and no additional browser plug-in support is required. Ajax applications are also friendly to search engines. For developers, the learning curves of Ajax technologies are also smooth and easy to use. This article briefly introduces all aspects of AJAX application development and related best practices, but does not discuss some details.
Ajax Introduction
The starting point of Ajax technology is to change the "Operation-wait for page loading-operation" user interaction mode when using traditional Web applications. This interaction mode interrupts normal user processes and reduces user productivity. The interaction mode of Ajax technology is "Operation-operation ". You do not need to wait explicitly for the page to be reloaded, but can constantly interact with the page. A part of the page is dynamically refreshed to provide feedback to users. The interaction process is smoother and smoother. This is an important reason for the popularity of Ajax technology.
Ajax is built on a series of standard technologies, including HTML, JavaScript, and CSS. Among these technologies, HTML exists as the skeleton of an application and displays the most basic content to users. CSS provides an easy-to-read style for HTML content. Javascript adds rich interactive behaviors to the application, providing a good user experience.
The emergence of Ajax technology allows the logic of a part of the application to be migrated from the server to the browser. The role of the browser has increased from simple page rendering and form processing to processing part of the business logic.
Generally, there are two types of AJAX application styles. One is to use only a small amount of Ajax technology to properly enhance user experience (Ajax lite ), in addition, Ajax is widely used to provide a similar user experience (Ajax deluxe) to desktop applications, such as right-clicking, dragging, and cascading menus. Developers should select the appropriate style based on the characteristics of the application.
Browser compatibility
Browser compatibility is an important issue for developing Ajax applications. Although Ajax technology is based on standard technologies such as HTML, JavaScript, and CSS, the implementation of these standards varies greatly from browser vendors. Different versions of the same browser may also be different. The new version may fix or cause new problems. However, the general trend is that browser implementations are becoming closer and closer to standards.
The first step to solve browser compatibility is to determine the type and version of the browser to be supported by the application. This decision depends on the target user of the application and the specific application requirements. For general Ajax applications, it can be determined based on the market share of the browser and the price required to support a browser. Graded browser support proposed by Yahoo is a good reference. It is a good choice from the-level browser. For specific application requirements, some Ajax applications that use ActiveX controls can only run on IE. For iPhone-oriented applications, you only need to consider mobile WebKit.
As far as the three components of Ajax applications are concerned, there are few issues with HTML compatibility. After all, the mainstream HTML 4.01 specifications have been around for 10 years. In JavaScript, the core part of the Javascript language is basically okay, while the compatibility between the Document Object Model (DOM) and the browser Object Model (BOM) is relatively high, this is mainly because the browser has different levels of support for specifications and their respective private implementations. Using a popular JavaScript library can solve these problems. CSS compatibility is currently the most problematic, and there is no better library support. The following describes the compatibility of CSS.
Semantic-rich HTML
The HTML language is easy to use. It is just a set of elements. You only need to understand the meaning of these elements and their attributes. These elements are both semantic-rich elements related to the document structure and page display. A good practice is to use only the elements related to the document structure and rich in semantics. This trend can also be seen from the history of HTML language specifications. The HTML language specification has a long history. In the original HTML draft and HTML 2.0, HTML only contains elements that describe the document structure. In HTML 3.2, many display-related elements are introduced. The HTML 4.01 specification attempts to solve this problem. Many display-related elements are marked as obsolete and are not recommended. HTML 5 goes further by introducing more semantic-rich elements and removing some obsolete elements in HTML 4.01. This practice further clarifies the roles and responsibilities of HTML and CSS in Ajax applications.
When writing HTML documents, you must first select the appropriate document type declaration (DTD ). Currently, the most appropriate HTML 4.01 transition type is <! Doctype HTML public "-// W3C // dtd html 4.01 transitional // en" "http://www.w3.org/TR/html4/loose.dtd">. When writing HTML documents, you need to use appropriate elements. Some elements in HTML specifications, such as <em>, <strong>, <abbr>, <BLOCKQUOTE>, <cite>, and <code>, are unfamiliar to developers. However, these elements are rich in semantics and are suitable for use in scenarios. If you are using common elements such as <div> and <span>, you need to use the class attribute rich in semantics to increase the semantics and describe the role of the element. After the HTML document is compiled, it is best to use the HTML document validator provided by W3C to verify the document.
CSS
CSS syntax is very simple and contains very few elements, the most important of which is the style rule set. A style rule set is a set of style declaration rules. Each style rule consists of a selector and a declaration. The selector is used to select elements in the document. These elements will be applied to the style declaration corresponding to the selector. Different CSS version specifications support different selector types. Use common and simple selector whenever possible to achieve better browser compatibility, such as ID selector, class selector, and element selector.
A major problem encountered when using CSS is browser compatibility. It is often the case that a style is normally applied on browser A and browser C, but not on browser B. When browser B is adjusted, an error occurs in browser C. The basic principle for solving this problem is to first determine several baseline browsers and develop basic layout styles. The baseline browser is generally a browser with better support for CSS specifications. The basic layout style sheet ensures that the page layout applied on the baseline browser is correct. Currently, browsers have the worst compatibility in CSS page layout, especially in Box Model and floating positioning. There is basically no problem with the display style, such as the font size and color.
The next step is to make the basic layout style sheet work correctly on other browsers except the baseline browser. In this case, you need to apply special styles to browsers of a certain version to correct style inconsistencies. One way is to use some hack ). The trick is to identify the browser and apply the style by using imperfect CSS specifications or implementation bugs. Another method is to use JavaScript to detect the current browser and apply the style. Moves may become unavailable as the browser version is updated, so try to use them as little as possible.
In general Ajax applications, ie 6 is the most common application method. Because IE 6 does not fully support CSS specifications and has many bugs, there are still a large number of users in IE 6, so it is necessary to support them. A better way to apply a special style to IE is to use the conditional annotation unique to IE.
When many CSS files are contained in an application, it is difficult to develop and maintain these CSS files. One solution is to introduce the object-oriented idea into the CSS compiling process. The two important principles are componentization and single responsibility. Componentization is to develop style components for certain elements on the page. These style components can be used in any combination on different pages. A single responsibility refers to the separation of the style indicating the structure and appearance. The style related to the structure includes the size and position, and the appearance style includes the font size, color, and background image.
Dom query and operations
Dom operations are the basis for implementing dynamic and partial page refreshes in Ajax applications. Dom defines the logical structure of the document and the methods for accessing and operating the document. With Dom, developers can freely navigate the document, or add, update, and delete elements and content. You can query and operate documents through APIS provided by Dom specifications. However, Dom native APIs are cumbersome to use. It is best to use a javascript library for queries and operations.
Modifications to the current page through DOM operations usually occur in response to user events. Some of these Dom operations are implemented only on the browser side, and the other part requires support from the server side. The server can choose to return data or HTML fragments. The advantage of Returning data is that the transmitted data volume is small and can be easily integrated with third-party applications. The disadvantage is that the browser needs additional operations to complete the display. The browser can use Dom operations or template technology to generate HTML fragments. The server can also generate HTML fragments using templates such as JSP and Apache velocity and return them directly to the browser. The browser only needs to be used directly. The advantage of this approach is that the browser-side implementation is simple. The disadvantage is that the presentation-related logic exists on both the server side and the browser side, which is not easy to maintain.
Some good practices can improve the performance of Dom operations. First, use document fragment ). When you need to insert a large number of nodes, first add these nodes to a document segment, and then add this document segment to the document. This can reduce the page re-arrangement. The second is to use innerhtml to update the document content, which is faster than using Dom APIs. Finally, multiple elements with the same structure are created through clonenode.
Event Processing
Ajax applications interact with users by responding to user events. The browser is responsible for capturing user behaviors and generating various events, and the application handles these events. There are many types of events that can be generated in the browser. After an event is generated, it will be transmitted in the current document tree according to a certain process. The node generated by the event is called the target node. The Complete Event propagation process starts from the root node of the document to the target node (capture stage), and then forwards it back to the root node (bubble stage ). When an event is transmitted to a node, the binding method is triggered. (Ie only supports the bubble stage .) Note that the value of the object pointed to by this in the event processing method may be the current node or window object. You can use the support provided by the Javascript library to bind event processing methods to avoid these inconsistencies.
When binding event processing methods, you can use the event propagation mechanism to reduce the number of event listeners. If you want to add a mouse click event to a series of <li> elements, you can add the event to its parent node <ul>. After processing an event, you can terminate the event propagation and prevent the browser's default behavior.
Select a suitable JavaScript framework
There are currently many JavaScript frameworks, both open-source and commercial. Popular ones include jquery, dojo, Yui, extjs, mootools, and prototype. The advantage of using a popular framework is that it has a relatively large community support and is easy to get help when encountering problems. Popular frameworks also have rich documents and examples. Different frameworks bring different implementation styles to applications. Jquery users have a special liking for the cascade of methods, while dojo fans tend to divide different parts of the page into dijit for implementation.
There are many factors to choose the framework, both technical and non-technical. Generally, lightweight frameworks, such as jquery and prototype, are easy to use, but few reusable components are available. However, for large frameworks such as dojo and extjs, the learning curve is steep, however, there are many reusable components that are suitable for rapid development of complex Ajax applications.
Build Process
Ajax applications also require a complete build process. The main purpose of the construction process is to improve the quality and performance of Ajax applications. The building process can include the following steps:
- Check the potential errors and code style of JavaScript code. By integrating jslint, you can find potential problems in the code.
- Javascript file merging, downgrading, and obfuscation. You can merge multiple JavaScript files to reduce the number of HTTP requests for page loading. by reducing the number of unnecessary blank characters and comments in JavaScript code, you can reduce the file size, reduce the download time. By obfuscation, you can replace meaningful variable names to further reduce the file size and protect the code from reverse engineering to a certain extent. There are many tools that can execute these operations, and Apache ant can merge them. jsmin and Yui compressor can reduce the file size, while dojo shrinksafe can be confused.
- CSS file merging and reduction. Similar to Javascript, CSS files can also be merged and reduced to reduce the number of HTTP requests and file size. Yui compressor can reduce CSS.
- Image File compression. By converting and compressing image files, you can reduce the size of image files without losing quality.
Test
Ajax application testing includes two parts: Server and browser. For the server side, the testing technology and tools are mature. You only need to select based on the technology used by the server. An important principle is to try to implement loose coupling between the server and the browser to facilitate testing. From this perspective, it is better for the server to return data, rather than HTML fragments. You can use tools to test whether the results returned by the server are correct.
Browser tests are not ideal. There are already some unit testing frameworks, such as qunit and dojo D. O. H, and some integration testing tools, such as DOH robot and selenium. For unit testing, it is easy to implement pure logic code that is only implemented using JavaScript, and it is difficult to implement code that contains interaction with nodes on the page. Both unit testing and integration testing are currently not highly automated.
To facilitate testing, the coupling between various parts of Ajax applications should be as small as possible. The method body of event handling methods should be as simple as possible.
Debugging
Debugging of Ajax applications has always been a troublesome problem. The main reason is that there are various compatibility problems between different browsers, and there will be many differences between different versions of the same browser. In order to achieve consistent results on the supported browsers, developers often have a hard time. The current situation is much better. Different browsers have their own debugging tools, such as firebug on Firefox and developer toolbar on IE. When a problem occurs, you can use these tools to directly modify the DOM structure and CSS style on the page for testing. Find the correct solution and use the code to implement it. Many tools support directly entering JavaScript statements on the console for execution. In this way, you can quickly view the variable values in the program and call the JavaScript method to change the internal state of the application, to identify the cause of the problem.
Memory leakage
The Web application memory leakage problem persists. The emergence of Ajax applications further exposes this problem. Currently, many Ajax applications are single-page applications (SPA ). Users usually use a single page for a long time without closing the browser. Some small memory leaks generated during user operations will accumulate, resulting in increasing browser memory usage and slow Application Operation.
In the face of Memory leakage, pay attention to the following points:
- Familiar with common memory leakage modes. A typical example is the circular reference that contains DOM nodes due to incorrect use of closures. This problem can be solved by interrupting cyclic references.
- A large part of Memory leakage is related to DOM nodes. Do not add additional attributes to Dom node objects, especially Javascript methods.
- When a memory leak occurs, use drip and other tools to locate the leaked node and correct it.
Security
The emergence of Ajax does not solve some existing security problems, but also brings some new security risks. Security issues such as cross-site scripting (XSS), SQL injection, and cross-site Request Forgery (csrf) in traditional Web applications still need to be addressed in Ajax applications. For XSS, the general solution is to trust any user input. Escape all things during output ). Only restore escaping for things that are clearly known to be safe (whitelist ). The csrf solution is to add a verification token for all requests to ensure that the request comes from its own site.
The new security risks brought by Ajax are mainly related to JSON. Some Ajax applications expose JSON data on the server side. Jsonp allows you to use the <SCRIPT> label to obtain data, which is not affected by the browser's same-origin policy. However, jsonp may cause data to be stolen by malicious third parties. Attackers may also steal data by redefining JavaScript Object methods (such as array.
Performance
The performance of Ajax applications is a very important aspect. The performance factor should be taken into account on the first day of application development, and throughout the development process. If performance is considered at the end of development, it may be in a dilemma. On the one hand, application performance cannot meet user requirements, resulting in user complaints and loss. On the other hand, to improve performance, the existing architecture of the application needs to be greatly or even disruptive.
The performance of Ajax applications is determined by the frontend. There are several basic principles below:
- Reduces the number of interactions with the server and the size of data. This mainly reduces the number of HTTP requests sent by the browser and the size of the data returned by the server. The merging and reduction of JavaScript and CSS files mentioned above serves this purpose.
- Page progressive enhancement. In Ajax applications, the content contained in HTML documents is the most important for users, while CSS helps users conveniently view HTML documents. Therefore, the two are prioritized. JavaScript files can be loaded later or delayed. Therefore, in HTML documents, reference to CSS files should be placed above the document, that is, the
Google's Steve Souders has made a lot of pioneering work in the field of front-end performance. The two books he wrote, "high-performance websites" and "Faster websites", are excellent summative materials and deserve further study.
Personal Profile
Cheng Fu is currently at the IBM China Development Center and participates in the development of IBM products. Rich experience in front-end development and the dojo framework. I am also interested in the emerging Web 2.0 technology. His personal website is http://www.cheng-fu.com.
References
- Ajax application Style
- Browser compatibility tables
- HTML 4.01 Specification
- Semantic-rich HTML
- Ecmascript Language Specification Version 5
- Object-oriented CSS
- Proficient in CSS-advanced Web Standard Solutions
- Pro CSS and HTML Design Patterns
- Memory Leak patterns in Javascript
- Understanding and solving Internet Explorer leak patterns
- XSS cheat sheet
- Ajax Security
- Unit testing Web 2.0 applications using the dojo objective harness
- High Performance Web Sites