This article focuses on client-side performance, server-side performance, and Network performance. The content framework is drawn from the Yahoo Developer Network and includes 35 front-end performance optimization best practices in seven categories, supplemented with relevant or more mainstream technology content.

An important indicator of front-end performance is page load time, which is not only relevant to user experience, but also a factor in search engine rankings.

  • Data from Google shows that a page with 10 pieces of data that load in 0.4 seconds turns into 30 pieces of data that load in 0.9 seconds, and traffic and AD revenue drop by 90%.
  • When the Google Map homepage file size was reduced from 100KB to 70-80KB, traffic increased by 10% in the first week and 25% in the next three weeks.
  • According to Amazon, an increase of 100 milliseconds in load time leads to a 1% drop in sales.

The above data further proves that “loading time is money” and front-end optimization is mainly focused on improving loading speed.

First, page content

(1) Reduce the number of HTTP requests

80% of the response time on the Web front end is spent downloading images, styles, scripts, and other resources. The most straightforward way is to reduce the amount of resources a page needs, but that’s not practical. Therefore, the main ways to reduce the number of HTTP requests are:

Merge JS/CSS files. Server side (CDN) automatic merge, a Node.js-based file merge tool that reduces the number of requests by putting all scripts in one file.

Use CSS Sprite to combine background images into a single file and control the display through background-image and background-position

Inline images (Base64 encoded). Embed images in HTML or CSS using the Data URI scheme; Or embed CSS, JS, and images directly into HTML, which increases file size and may cause browser compatibility and other performance issues.

Reducing the number of HTTP requests to a page is a starting point, and an important guideline for improving the speed of first visits to your site.

(2) Reduce DNS queries

After the user enters the URL, the browser must first query the IP address of the server corresponding to the hostname, which usually takes 20-120 milliseconds. The browser cannot download any data from the server until the DNS query is complete.

Based on performance considerations, ISPs, Lans, operating systems, and browsers all have corresponding DNS caching mechanisms.

  • The IE cache lasts for 30 minutes, which can be set by DnsCacheTimeout in the registry.
  • The Firefox cache for 1 minute, through the network. DnsCacheExpiration configuration;

In addition, reducing the number of different host names reduces DNS lookups. Reducing the number of different host names also reduces the number of components on a page that can be downloaded in parallel. Avoiding DNS lookups reduces the response time, while reducing the number of parallel downloads increases the response time. The principle is to spread components over two to four host names, which is a compromise between reducing DNS lookups and allowing high concurrent downloads.

(3) Avoid redirects

HTTP redirection is implemented using 301/302 status codes. Here is an HTTP header with a 301 status code

HTTP / 1.1 301 version Permanently Location: http://example.com/newuri the content-type: text/HTMLCopy the code

The browser automatically jumps to the URL specified in the Location field. All the information needed for a redirect is in the HTTP header, and the response body is generally empty. Additional HTTP headers, such as Expires and cache-Control, also represent redirects. There are other ways to jump: refresh meta tags and JavaScript, but if you have to do redirection, it’s best to use the standard 3xxHTTP status code, mainly to make the back button work.

The client receives the redirected response from the server and sends the request again based on the address of Location in the response header. Redirection can affect the user experience, especially if the user is redirected multiple times, and the user sees nothing for a period of time, except that the browser progress bar keeps refreshing.

  • The most wasteful redirection happens frequently and is easily overlooked: it should be added at the end of the URL/But not added. For example, accesshttp://astrology.yahoo.com/astrologyWill be301Redirected tohttp://astrology.yahoo.com/astrology/(Note the/at the end). If you use Apache, you can solve this problem with Alias or mod_rewrite or DirectorySlash.
  • Web site domain name changes: CNAME jumps in combination with Alias or mod_rewrite or some other server equivalent.

(4) Caching Ajax requests

The most important optimization is caching the response results. With an Expires or cache-control HTTP header that hasn’t expired, the previous resource can be read from the Cache. The browser must be informed whether to continue with the previously cached resource response or to request a new one. You can do this by adding a timestamp to the resource’s Ajax URL indicating when the user resource was last modified. If the resource has not been modified since the last download and the timestamp is unchanged, the resource will be read directly from the browser cache, avoiding an additional HTTP round-trip cost. See server-Add Expires or Cache response headers for details.

(5) Delayed loading

What is absolutely necessary for a page to load initially? Resources not listed in the answer can be lazily loaded. Such as:

  • Data, styles, scripts, pictures, etc. not used on the first screen;
  • Content that is displayed only when the user interacts.

Sites developed with the philosophy of “progressive enhancement” : JavaScript is used to enhance the user experience, but works fine without JavaScript, and can be lazily loaded.

Reduce the number of DOM elements initially rendered and increase speed by placing HTML outside the first screen in unrendered elements, such as hidden

(6) preloading

Preloading uses idle browser time to request resources to be used in the future so that users can respond more quickly when they visit the next page.

  • Unconditional preloading: Fetching additional resources immediately after a page is loaded. In the case of Google.com, a Sprite image will be downloaded immediately after the home page is loaded. This image is not required for the home page, but is needed for the search results page.
  • Conditional preloading: Preloads related resources based on user behaviors. For example, when search.yahoo.com starts typing, additional resources load. Browsers like Chrome have a similar mechanism for the address bar.
  • Conspiracy preloading: preloading a new version of a page just before it goes live. After the revision of the site due to cache, use habits and other reasons, there will be faster and smoother feedback of the old version of the site. To alleviate this problem, the old version can cache some resources of the new version to the client before the new version is released, so that the new version can be loaded more quickly after the official launch.

(7) Reduce DOM elements

Complex pages not only download more bytes, but JavaScript DOM manipulation is slower. For example, adding an event handler can make a big difference in page speed between 500 elements and 5,000 elements.

Consider removing unnecessary tags from the following perspectives:

  • Are you still using table layouts?
  • I’m going to cram in more<div>Just to deal with layout issues? There may be better, more semantic markup.
  • There is no need to add extra elements, such as clearing floats, to functions that can be implemented with pseudo-elements.

To calculate how many DOM elements are in the page, enter the following code in the browser console:

document.getElementsByTagName(‘*’).length;

Why not use a table layout?

  • More tags, increased file size;
  • Not easy to maintain and cannot adapt to responsive design;
  • For performance reasons, the default table layout algorithm produces a lot of redrawing

(8) Divide content into different domain names

Browsers generally limit the number of parallel threads per domain (typically 6 or less), and use different domains to maximize download threads, but keep them within 2-4 domains to avoid DNS query wastage.

For example, dynamic content is on csspod.com and static resources are on static.csspod.com. This can also disable cookies in static resource domains to reduce data transfer, as shown in Cookie optimization.

(9) Minimize the use of IFrame

You can use iframe to insert an HTML document into a parent document. It’s important to understand how iframe works and use it efficiently.

Advantages of

  • Can be used to load slow third-party resources, such as ads, badges;
  • Can be used as a safety sandbox;
  • Scripts can be downloaded in parallel.

Disadvantages of

  • Expensive to load, even for empty pages;
  • The blocking page load event is triggered.

The parent page does not trigger the load event until the Iframe is fully loaded. Safari and Chrome use JavaScript to dynamically set iframe SRC to avoid this problem.

  • Lack of semantics.

(10) Avoid 404 errors

HTTP requests are expensive, and returning invalid responses (such as 404 not found) is unnecessary, degrading the user experience, and unhelpful. Some sites have cool 404 pages with prompts that help improve the user experience, but still waste server resources. Especially bad is when an external script returns a 404, which not only blocks other resources from downloading, but the browser tries to parse the 404 page as JavaScript, consuming even more resources.

Ii. Server

(1) Use CDN

The physical distance between the user and the server also has an impact on response time. Deploying content on multiple geographically dispersed servers allows users to load pages faster. But how?

80-90% of a website’s response time is spent downloading resources, and reducing resource download time is the golden rule of performance optimization. Compared with the complexity and huge investment of distributed architecture, static content delivery network (CDN) can effectively improve the loading speed with lower investment.

A Content delivery network (CDN) is a group of geographically dispersed Web servers that deliver content to users more efficiently. Typically, the server chosen to send the content is based on a measure of network distance. For example, select the server with the least hops or the fastest response time.

(2) Add Expires or Cache-control headers

  • Static content: Set the Expires header to a time far in the future to implement the “never expire” policy;
  • Dynamic content: Set the appropriate cache-control response header to allow the browser to conditionally issue the request.

The cache-control header is defined in the HTTP/1.1 specification, replacing the previous headers (e.g. Expires, Pragma) used to define response caching policies. Cache-control is supported by all current browsers, so using it is sufficient.

(3) Enable Gzip

Front-end engineers can find ways to significantly reduce the time it takes to send HTTP requests and responses over the network. Of course, the bandwidth speed of the end user, the isp, the distance of the peer exchange point, etc., are all beyond the control of the development team. But there are other factors that can affect response time. Compression can reduce response time by reducing the size of HTTP responses.

Gzip compression can typically reduce response size by up to 70% and possibly as much as 90% for some files, making it more efficient than Deflate. Major Web servers have modules, and most browsers support GZIP decoding. Therefore, compression should be enabled for text-type content such as HTML, CSS, JS, XML, JSON, etc.

Attention!!!!!! Do not use gzip for images and PDF files. They are already compressed, so using gzip compression not only wastes CPU resources, but can also increase file size.

Since HTTP/1.1, Web clients have had accept-Encoding HTTP request headers that support compression.

Accept-Encoding: gzip, deflate

If the Web server sees the request header, it compresses the response in a way that the client lists. The Web server notifys the client through the Content-Encoding response header.

Content-Encoding: gzip

(4) Configure Etag

Entity tags (ETags) are a mechanism used by the server and the browser to determine whether components in the browser cache match components in the source server (” entities “are components: images, scripts, style sheets, and so on). Adding ETags provides an entity validation mechanism that is more flexible than the last modified date. An ETag is a string that acts as a unique identifier for a specific version of a component. The only format constraint is that the string must be enclosed in quotes, and the source server specifies the component’s ETag with the ETag in the corresponding header.

HTTP/1.1 200 OK
      Last-Modified: Tue, 12 Dec 2006 03:03:59 GMT
      ETag: "10c24bc-4ab-457e1c1f"
      Content-Length: 12195
Copy the code

Then, If the browser has to validate a component, it uses the if-none-match request header to pass the ETag back to the source server. If the ETags match is successful, a 304 status code is returned, reducing the response body by 12,195 bytes. Etag enables the server to determine whether the requested content is updated by identifying the version of the file. If not, the server responds to 304 to avoid re-downloading.

GET /i/yahoo.gif HTTP/1.1
      Host: us.yimg.com
      If-Modified-Since: Tue, 12 Dec 2006 03:03:59 GMT
      If-None-Match: "10c24bc-4ab-457e1c1f"HTTP / 1.1 304 Not ModifiedCopy the code

(5) Flush the buffer early

When a user requests a page, the server typically takes 200 to 500 milliseconds to assemble an HTML page. During this time, the browser is idle, waiting for data. Using the flush() function in PHP, you can send a portion of the prepared HTML to the browser so that the browser can start retrieving resources ahead of time while the server is still busy processing the remaining pages.

Consider outputting a buffer after the . HTML heads are generally easier to generate and are sent first so that the browser can start retrieving the CSS referenced in the .

Example:

<! -- css, js --> </head> <? php flush(); ? > <body> <! -- content -->Copy the code

(6) Ajax requests use the GET method

The browser executes the XMLHttpRequest POST request in two steps, sending the Http Header first and then the data. GET uses only one TCP packet (Http Header and data) to send data, so the GET method is preferred.

According to the HTTP specification, GET is used to GET data, and POST is used to send data to the server, so using GET when Ajax requests data is more in line with the specification.

(7) Avoid image SRC being empty

A string with an empty SRC attribute value can appear in one of two ways:

HTML:

<img src="" />
Copy the code

JavaScript:

var img = new Image(); 
img.src = "";
Copy the code

Although the SRC attribute is an empty string, the browser still makes an HTTP request to the server:

  • IE sends a request to the directory where the page resides.
  • Safari, Chrome, and Firefox send requests to the page itself;
  • Opera does nothing.

The consequences of an empty SRC request are not trivial:

  • Cause unexpected traffic burden to the server, especially when the time PV is large;
  • Waste server computing resources;
  • An error may occur.

The empty href attribute presents a similar problem. When the user clicks on an empty link, the browser also sends an HTTP request to the server, which can prevent the default behavior of an empty link through JavaScript.

Three, Cookie,

(1) Reduce Cookie size

Cookies are used for authentication, personalization and many other purposes. Cookies are sent back and forth between the server and the browser through HTTP headers, and reducing Cookie size can reduce their impact on response time.

  • Remove unnecessary cookies;
  • Minimize Cookie size;
  • Set the domain level of cookies. If not necessary, do not affect the sub-domain.
  • Set an appropriate expiration time.

(2) Static resources use cookie-free domain names

Static resources generally do not need to use cookies. They can be stored on a cookie-free server that uses a secondary domain name or a special domain name to reduce the traffic waste caused by Cookie transmission and improve the response speed.

Four, CSS,

(1) Put the style sheet in<head>In the

Placing the stylesheet in allows the page to render incrementally, providing visual feedback early on and giving the user the impression that it loads quickly.

This is especially important for pages with a lot of content, where the user can see what has already been downloaded and rendered instead of staring at a blank screen.

If the style sheet is placed at the bottom of the page, some browsers will render the page after the CSS is loaded to reduce redrawing, leaving the user with a blank screen and a poor user experience. Placing the stylesheet in the HEAD section of the document makes the page seem to load faster.

(2) Don’t use CSS expressions

CSS expressions can execute JavaScript in CSS, only supported by IE5-IE7, IE8 standard mode is deprecated. CSS expressions are executed more frequently than expected, and are executed repeatedly during page scrolling and mouse movement, resulting in a significant performance penalty.

(3) Use<link>alternative@import

For some versions of IE, @import behaves as if placed at the bottom of the page. So, don’t use it.

(4) Do not use filter

AlphaImageLoader is a proprietary technology for IE5.5-IE8, like CSS expressions, put in the museum. IE’s proprietary AlphaImageLoader filter can be used to fix translucent PNG images in previous versions of IE7. This filter blocks the render during image loading, jams the browser, increases memory consumption and is applied to every element, not every image, so there are a lot of problems.

Attention!! This is not a CSS3 Filter

Fifth, Javasript

(1) Place the script at the bottom of the page

When the browser downloads scripts, other resources, even those from different domain names, are blocked. Therefore, it is best to place scripts at the bottom to speed up page loading.

For special scenarios where scripts cannot be placed at the bottom of a page, consider the following attributes of

  • The defer attribute;
  • HTML5 new async property.

2) Use external JavaScript and CSS

External JavaScript and CSS files can be cached by the browser, reused across different pages, and reduced in page size.

In practice, of course, you also need to consider how reusable your code is. If it’s just code used on a page, consider embedding it in the page to reduce the number of HTTP requests. Alternatively, you can pre-load resources for sub-pages after the home page is loaded.

(3) Compress JavaScript and CSS

Compressed code can remove non-functional characters (comments, Spaces, blank lines, etc.), reduce file size, and improve loading speed.

Thanks to the popularity of Node.js, many efficient and easy-to-use front-end optimization tools have emerged in the open source community, including JavaScript and CSS compression classes, such as [UglifyJS 2] (github.com/mishoo/Ugli…). , CSSO, CSSNano, etc.

Embedded CSS and JavaScript can also be compressed using tools such as HTMLmin.

These projects have versions of popular build tools such as Gulp and Webpack.

(4) Remove duplicate scripts

Not only do repeated scripts generate unnecessary HTTP requests, but repeated parsing execution wastes time and computing resources.

(5) Reduce DOM operations

JavaScript is slow to manipulate the DOM, especially if there are many DOM nodes.

Note when using:

  • Caches already accessed elements;
  • Use The DocumentFragment to temporarily store DOM, and then insert DOM tree after sorting;
  • Operation className instead of reading and writing style multiple times;
  • Avoid using JavaScript to fix layouts.

(6) Use efficient event processing

  • Reduce the number of nodes that bind events to listen on, such as through event delegates;
  • Handle events as early as possible, at DOMContentLoaded, rather than after load.

Six, pictures,

(1) Optimize the picture

Try converting GIF to PNG to see if you save space. Run PngCrush (or any other PNG optimization tool) on all PNG images.

The tools listed in YDN are not easy to use. You are advised to use the following tools

  • imagemin
  • imageoptim.com

TODO:

  • PNG ultimate optimization;
  • Webp related content;
  • SVG related content.

PNG Ultimate optimization

  • Most Effective Method to Reduce and Optimize PNG Images
  • Clever PNG Optimization Techniques

(2) Optimize CSS Sprite

  • Arrange images in Sprite horizontally, vertically increasing the size of the image.
  • In the Spirite, combining colors closer together can reduce the number of colors, ideally below 256 colors for the PNG8 format;
  • Don’t leave large gaps in the middle of the Spirite image. Reducing the gap, while not affecting file size much, can reduce the memory consumption of user agents decompressing images into pixel images, making it more mobile-friendly.

(3) Do not zoom images in HTML

Do not use the width and height of to zoom images. If you use small images, use the corresponding size. If you need

<img width="100" height="100" src="mycat.jpg" alt="My Cat" />

The image itself (mycat.jpg) should be 100x100px, not 500x500px.

Many CMS and CDNS provide image cropping.

Add: Set the width and height of the image, so that the browser will not redraw the area reserved for the image according to the “guess” width and height difference.

(4) Use a small, cacheable Favicon.ico

Favicon.ico is generally stored at the root of the site, and browsers try to request this file whether or not it is set up on the page.

So make sure this icon:

  • Exists (avoid 404);
  • As small as possible, preferably less than 1K;
  • Set a long expiration time.

For newer browsers, you can use a FAVicon in PNG format.

Seven, mobile terminal

(1) Ensure that all components are less than 25K

This limitation is due to the fact that the iPhone cannot cache components larger than 25K, which is the uncompressed size. That’s why curtailing content itself is important, as gZIP alone may not be enough.

Ensure that all components are smaller than 25K

(2) Package the content as multipart documents

Packaged into a composite document like E-mail with attachments, multiple components can be retrieved with a single HTTP request (remember: HTTP requests are expensive). When using this approach, check to see if the user agent supports it (iPhone doesn’t).

conclusion

Write here, Yahoo’s 35 catch-22 is finished introduction. Although there are many items, after classification, it can be found that the main entry point of performance optimization can be considered from the following aspects:

  • Compression optimization of the size of the resource itself (find ways to reduce the size of the resource)
  • The entire process of a network request (from entering and sending the request in the URL address bar to returning the response packet)
  • The entire browser rendering process (every step of the browser rendering process once you get the resource)

Therefore, a thorough understanding of the HTTP request process as well as the browser rendering process is necessary to thoroughly understand optimization methods.

Originally from my blog:

Yahoo’s 35 Catch-22 — Front-end performance Optimization