The only thing that's going to break: 13 optimizations to improve Web applications

Source: Internet
Author: User
Tags script tag amazon cloudfront nginx reverse proxy



Over time, WEB applications are more interactive than ever. Performance can help you dramatically improve the end-user experience. Read the following tips and learn what you can do to improve latency, rendering time, and overall performance.


Faster Web Apps


Optimizing WEB applications is an arduous task. Web applications are not only part of the client-and server-side components, but are often built from a variety of technology stacks: databases, back-end components (typically built on different technology architectures), and front-end (HTML + JavaScript + CSS + translator). The runtime is also changeable: Ios,android,chrome,firefox,edge. If you've ever worked on a different single huge platform, typically performance optimizations are only for a single goal (or even just a single version of the target), but now you might realize that the task complexity is far beyond that. That's right. But there are also some general optimization guides that can greatly optimize an application. We will explore the contents of these guides in the following chapters.


Premature optimization?


The hardest part of optimization is how to optimize at the most appropriate time in the development life cycle. Donald Knuth has a famous saying: "Premature optimization is the root of all evils." The reason behind this sentence is very simple: because accidentally will waste time to optimize a 1% of the place, but the results will not have any significant impact on performance. At the same time, some optimizations hinder readability or maintainability, and even introduce new bugs. In other words, optimization should not be considered "to mean the best performance of the application", but "to explore the right way to optimize the application and get the most benefit". In other words, blind optimization can lead to loss of efficiency, while the benefits are small. Keep this in mind when you apply the following techniques. Your best friend is the analysis tool: Find the performance points you can optimize to achieve maximum improvement without compromising the process or maintainability of application development.


1. JavaScript Compression and Module packaging


JavaScript applications are distributed in the form of source code, and the efficiency of source parsing is lower than byte code. For a small piece of script, the difference is negligible. However, for larger applications, the size of the script can have a negative impact on the app startup time. In fact, one of the most significant improvements expected to be achieved with WebAssembly is the faster start-up time.



Module packaging, on the other hand, is used to package different scripts together and put them in the same file. Fewer HTTP requests and individual file parsing can reduce load times. Typically, a single tool can handle packaging and compression. Webpack is one of them.
Example code:



 
function insert(i) { document.write("Sample " + i);
} for(var i = 0; i < 30; ++i) {
    insert(i);
}


The results are as follows:


! function(r){
 function t(o){
if(E[o])returnE[o].exports;
varn=e[o]={
exports:{},id:o,loaded:!1};
returnR[o].call (n.exports,n,n.exports,t), n.loaded=!0, n.exports}
vare={};returnt.m=r,t.c=e,t.p="", T (0)}(
[ function(r,t){
 function e(r){
document.write ("Sample"+R)}
 for(varo=0; ->o;++o) e (o)}]);//# Sourcemappingurl=bundle.min.js.map

Further packaging



You can also use Webpack to package CSS files and merge pictures. These features can help improve startup time. Take a look at the Webpack documentation to do some testing!


2. Load Resources On Demand


Load-on-demand or lazy loading of resources (especially pictures) can help your WEB application get better performance overall. Lazy loading has a significant three benefits for pages that use a large number of images:


    • Reduce the number of concurrent requests made to the server (which makes the rest of the page load faster)
    • Reduce browser memory usage (fewer images, less memory)
    • Reduce server-side load


The general idea is to load images or resources (such as videos) only when necessary, such as when they are first displayed, or when they are to be displayed. Because this approach is closely related to the way you build your station, lazy-loaded solutions often need to be implemented with the help of other libraries ' plugins or extensions. For example, React-lazy-load is a plugin for handling react lazy loading images:




const MyComponent = () => (
  <div>
    Scroll to load images.
    <div className="filler" />
    <LazyLoad height={762} offsetVertical={300}>
      <img src=‘http://apod.nasa.gov/apod/image/1502/HDR_MVMQ20Feb2015ouellet1024.jpg‘ />
    </LazyLoad>
    (...)
3. Use the Array-ids when using the DOM operation Library


If you are using React,ember,angular or other DOM operations libraries, using Array-ids (or the track-by feature in Angular 1.x) is very useful for high performance, especially for dynamic web pages. We've seen the effect of this feature in the previous program Metrics article: more benchmarks:virtual DOM vs Angular 1 & 2 vs Mithril.js vs Cito.js vs the Rest (UPDA Ted and Improved!).






The main concept behind this feature is to reuse existing nodes as much as possible. Array IDs allows the DOM operations engine to "know" when a node can be mapped to an element in an array. Without array-ids or track-by, most libraries will be reordered to destroy existing nodes and recreate new ones. This is a very lossy performance.


4. Caching


Caches is a component used to store static data that is frequently accessed, so that subsequent requests for that data can be answered more quickly, or the request is more efficient. Because WEB applications are composed of many removable parts, the cache can exist in many parts of the architecture. For example, a cache can be placed between a dynamic content server and a client to avoid public requests to reduce server load while improving response time. Other caches may be placed in the code to optimize some common patterns for script access, and some caches may be placed before the database or long running processes.



In short, using caching in a Web app is a great way to improve response times and reduce CPU usage. The difficulty is figuring out where to place the cache in the schema. Once again, the answer is performance analysis: Where are the common bottlenecks? Can data or results be cached? Are they too easy to expire? These are tricky questions that need to be answered 1.1 points from the principle.



The use of caching is creative in the WEB environment. For example, Basket.js is a library that uses local Storage to cache application scripts. So your Web app can be loaded almost instantaneously when you run the script for the second time.



One of the most popular caching services today is Amazon's CloudFront. CloudFront, like the usual content distribution network (CDN) usage, can be set as a cache of dynamic content.


5. Enable HTTP/2


More and more browsers are starting to support HTTP/2. This may not sound necessary, but HTTP/2 brings a number of benefits to concurrent connectivity issues for the same server. In other words, if there are a lot of small resources that need to be loaded (if you pack it up, it's not necessary), http/2 seconds to kill http/1 in terms of latency and performance. Try Akamai's HTTP/2 demo to see the difference in the latest browser.





6. Application Performance Analysis


Performance analysis is an important step in optimizing any application. As mentioned in the introduction, blindly trying to optimize applications often results in inefficient waste, insignificant gains, and poorer maintainability. Performing performance analysis is an important step in identifying your application's problems.



For WEB applications, latency is one of the biggest complaints, so you need to make sure that the data is loaded and displayed as fast as possible. Chrome offers great performance analysis tools. In particular, the timeline and network views in Chrome Dev Tools are a great help in locating latency issues:






The timeline view can help you find long-running operations.






The network view can help identify additional delays caused by slow requests or serial access to one end point.



With proper analysis, memory is another piece of revenue that can be earned. If you're running a page with a lot of virtual elements (huge dynamic tables) or interactive elements (such as games), memory optimization can get less lag and higher frame rates. From our recent article 4 Types of Memory Leaks in JavaScript and Get Rid of them, there is a deeper understanding of how Chrome's development tools are used.



CPU performance analysis can also be found in Chrome Dev Tools. Take a look at this article from Google's Official document Profiling JavaScript performance.






Finding the center of performance loss allows you to efficiently reach your optimization goals.



Performance analysis of the backend is more difficult. Typically, identifying a time-consuming request can give you a clear picture of which service to prioritize. For back-end analysis tools, it depends on the technology stack being built.


A note on the algorithm


In most cases, choosing a better algorithm can yield greater benefits than the specific optimization strategy that is implemented around a small cost center. In a way, CPU and memory analysis should help you to find a big performance bottleneck. When these bottlenecks are not related to coding problems, it is time to consider different algorithms.


7. Using the load Balancing scheme


We briefly mentioned the content distribution network (CDNS) when we discussed caching earlier. Assigning loads to different servers (or even different geographic regions) can give your users better latency, but this is a long way to go, especially when dealing with a lot of concurrent connections.



Load balancing is as simple as using a round-robin (loop) solution, either based on an nginx reverse proxy, or based on a mature distributed network, such as Cloudflare or Amazon CloudFront.






The above diagram comes from Citrix. In order for load balancing to be truly effective, dynamic content and static content should be split into easy concurrent access. In other words, the element's string access weakens the load balancer's ability to offload optimally. At the same time, concurrent access to resources can improve startup time.



While load balancing can be complex. A data model that is unfriendly to the final consistency algorithm, or a cache, can make things more difficult. Fortunately, most applications need only a high level of consistency for the simplified datasets. If your application is not designed like this, it is necessary to refactor it.


8. Consider homogeneous JavaScript for faster start-up time


One way to improve the look and feel of WEB applications is to reduce startup time or reduce page rendering time. This is especially important for emerging single-page applications, which require a large number of tasks on the client side. Doing more on the client usually means downloading more information before the first rendering is executed. Homogeneous JavaScript solves this problem: since JavaScript can run both on the client and server side, this makes it possible to perform the first rendering of the page on the server side, first sending the rendered page out and then being taken over by the client's script. This limits the backend used (the JAVASCRIPT framework that supports the feature must be used), but it provides a better user experience. For example, React is good for doing this, as shown in the following code:


 
 
var React = require(‘react/addons‘);
var ReactApp = React.createFactory(require(‘../components/ReactApp‘).ReactApp);

module.exports = function(app) {

    app.get(‘/‘, function(req, res){
        // React.renderToString takes your component
        // and generates the markup
        var reactHtml = React.renderToString(ReactApp({}));
        // Output html rendered by react
        // console.log(myAppHtml);
        res.render(‘index.ejs‘, {reactOutput: reactHtml});
    });

};


Meteor.js has great support for client and server-side JavaScript mixing.


 
if (Meteor.isClient) {
  Template.hello.greeting = function () { return "Welcome to myapp.";
  };

  Template.hello.events({ ‘click input‘: function () { // template data, if any, is available in ‘this‘ if (typeof console !== ‘undefined‘)
        console.log("You pressed the button");
    }
  });
} if (Meteor.isServer) {
  Meteor.startup(function () { // code to run on server at startup });
}


However, in order to support server-side rendering, plug-ins such as METEOR-SSR are required.
Thank you gabrielpoca that point in the comments. If you have complex or medium-sized applications that need to support homogeneous deployment, try this and you might be surprised.


9. Using indexes to speed up database queries


If you need to solve a time-consuming problem with database queries (analyze your app to see if this is the case!). ), it's time to find out how to speed up the database. Each database and data model has its own trade-offs. Database optimization is a topic in every respect: data models, database types, implementation scenarios, and so on. Speed-up may not be so simple. But here's a suggestion that might be useful for some databases: indexes. An index is a process, which is a fast-access data structure created by a database that maps from inside to a key (a column in a relational database) to improve the speed of retrieving related data. Indexes are supported in most modern databases. Indexes are not unique to document-based databases such as MongoDB, but also to relational databases (such as PostgreSQL).



To use the index to refine your query, you will need to look at the application's access patterns: What is the most common query, which key or column to perform the search, and so on.


10. Use a faster translation scheme


The JavaScript software technology stack is as complex as ever. And the need to improve the language itself adds to the complexity. Unfortunately, JavaScript as the target platform is also limited by the user's runtime. Although many improvements have been implemented in the form of ECMAScript 2015 (2016 in progress), it is often not possible to rely on this version for client-side code. This trend has prompted a series of translators: Tools for handling ECMAScript 2015 code and features missing from the ECMASCRIPT 5 structure. At the same time, module bindings and compression processing have also been integrated into this production process, known as the code version built for publishing. These tools can transform code and can affect the performance of the final code in a limited way. Google developer Paul Irish took some time to find out how these translation scenarios could affect performance and the size of the final code. While the benefits will be small in most cases, it is worth looking at the data before formally adopting a stack. For large applications, this distinction can have a significant impact.


11. Block rendering by avoiding or minimizing the use of JavaScript and CSS


Both JavaScript and CSS resources block rendering of the page. By taking certain rules, you can ensure that your scripts and CSS are handled as quickly as possible so that your browser can display the content of your site.



In the case of CSS it is very important that all CSS rules are not directly related to specific media, and the rules are only used to prioritize what you are going to display on the page. This can be done by using CSS media queries. Media queries tell the browser which CSS style sheets are applied to a particular display medium. For example, some rules for printing can be given a lower priority than for a screen display.



Media queries can be set as tag properties:



<link rel="stylesheet"type="text/css" media="only screen and (max-device-width: 480px)" href="mobile-device.css" />


When it comes to JavaScript, the key is to follow some rules for inline JavaScript (like code inline in an HTML file). Inline JavaScript should be as short as possible and put in place that does not block the rest of the page from parsing. In other words, inline JavaScript that is placed in the middle of the HTML tree will block the parser in this place and force it to wait until the script is executed. This can be a performance killer for performance if you arbitrarily put large blocks of code or many small blocks of code in the HTML file. Inline can effectively reduce the additional network requests for some specific scripts. But for reusable scripts or large blocks of code, this benefit can be negligible.



One way to prevent JavaScript from blocking the parser and renderer is to mark the script tag as asynchronous. This limits our access to the DOM but allows the browser to continue parsing and rendering the page regardless of the execution state of the script. In other words, to get the best start-up time, make sure those scripts that are not important for rendering are already marked asynchronously by the way the asynchronous attributes are.



<script src="async.js" async></script>
12. A recommendation for the future: using service workers + streaming


Jake Archibald A recent blog post detailing an interesting technique that can be used to speed up rendering time: Combining service workers and streams. The results are very compelling:



Unfortunately, the APIs required for this technique are not stable, which is why this is an interesting concept but there is no real reason for it to be applied. The idea is to place a service worker between the website and the client. This service worker can cache some data (such as headers and something that doesn't change frequently) while getting the missing information. The missing content can flow to the rendered page as quickly as possible.
Https://www.youtube.com/watch?v=Cjo9iq8k-bc


13. Update: Image encoding optimization


One of our readers points to a very important omission: Image coding optimization. PNGs and JPGs are encoded using suboptimal settings when the Web is published. By changing the encoder and its settings, you can get effective improvements for sites that require a large number of images. Popular solutions include OptiPNG and Jpegtran.
A Guide to PNG optimization describes in detail how optipng can be used to optimize PNGs.



The man page for Jpegtran provides a good introduction to some of its features.



If you find these guidelines too complex for your requirements, here are some online sites that can provide optimization services. There are also graphical interfaces like RIOT, which are very helpful for batch operations and results checking.


Extended Reading


You can read more in the links below and find tools to help you optimize your site:


    • Best practices to speeding up Your Website-yahoo Developer Network
    • Yslow-a tool that checks for Yahoo ' s recommended optimizations
    • Pagespeed Insights-google Developers
    • Pagespeed Tools-google Developers
    • HTTP/2: The long-awaited Sequel
Whisper: Common optimizations in Auth0


We are a WEB company. In this capacity, we have deployed some specific optimizations for some parts of our infrastructure. For example, on the login page you can find that, under the/learn path of our domain name (for example, single sign-on to the login page), we have a special optimization: To facilitate our use of CMS to create each article. Because the article has no central index, but in order to be able to be found by the search engine, using the Webtask crawler to pre-render each page and generate a static version then upload to our CDN. This reduces our stress on the server side, because there is no need to generate dynamic server-side content for each guest. It also improves latency (and isolates the security issues we find related to CMS).



For the documentation section, we're using homogeneous JavaScript, which gives us a great start-up time and makes it easy for our back-end and front-end teams to integrate.


Conclusion


As applications become larger and more complex, performance optimization is becoming increasingly important for Web development. Targeted improvements are essential in making any worthwhile time and potential future cost optimization attempts. WEB applications have already broken the boundaries of most static content, and learning common patterns for optimization is the biggest difference between delightful apps and completely unusable apps (this is the long-term way for your visitors to stay!). )。 No rule is absolute, but the intricacies of performance analysis and research on a particular software technology stack are the only way to find out how to optimize it. Have you ever found other suggestions that have a huge impact on your application? Please leave a message to let us know. Hack on!



Original translation address (with limitations)
Original address



The only thing that's going to break: 13 optimizations to improve Web applications


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.