Whether at work or in an interview, optimization of web front-end performance is very important, so what aspects should we start to optimize? This article will follow the 34 golden Rules — no, 35 now — that yahoo’s front-end performance team has put together.
Web content
1. Reduce the number of HTTP requests.
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.
Relevant schemes are as follows:
-
Merge files
-
CSS Sprites
-
Image mapping.
You can combine multiple images into a single image of the same total size, but reduce the number of requests and speed up page loading. Image maps are only useful when images are contiguous on a page, such as navigation bars. Setting coordinates for an Image map is tedious and error-prone, and navigation with an Image map is not easy, so it is not recommended.
See HTML image mapping for details
-
Inline images (Base64 encoded)
2. Reduce the number of DNS queries
Related schemes are as follows:
-
DNS cache
-
Reduce DNS lookups by reducing the number of different host names
Reducing the number of different host names also reduces the number of components a page can download in parallel, avoiding DNS lookups reduces response time, while reducing the number of parallel downloads increases response time. This is a compromise that simultaneously reduces DNS lookups and allows high concurrent downloads.
3. Avoid page redirection
When the client receives a jump reply from the server, the client sends the request again based on the address specified in location in the server reply, such as the following jump reply.
HTTP/1.1 301 Moved Permanently
Location: http://example.com/newuri
Content-Type: text/html
Copy the code
When the client receives this reply, the user can only wait for the client to send the request again, and some sites will even skip to the place where they want to take you. Of course, the user doesn’t see any page content at this point, just the browser’s progress bar that keeps refreshing.
Redirects slow down the user experience, inserting redirects between the user and the HTML document delays everything on the page, the page can’t be rendered, and components can’t start downloading until the HTML document is delivered to the browser. So avoid page hops.
4. Caching Ajax
Ajax can help us asynchronously download web content, but there are some web content that is asynchronous and the user is still waiting for it to return results, such as a drop-down list of the user’s contacts. So be careful to apply the following rules as much as possible to make Ajax responsive.
Related schemes are as follows:
- add
Expires
orCache-Control
The header enables the response to be cached by the client - Gzip compresses and transfers files
- Reducing DNS queries
- Compressed response content
- Avoid page hops
- Configuration ETags
5. Lazy loading
The discussion of lazy loading here requires that we know what the minimum set of content our web pages need to load initially is. The rest of the content can be pushed into a lazy-loaded collection.
Javascript is typically lazy to load content. A more radical approach is to develop a web page to make sure it works without Javascript, and then use lazy-loading scripts for advanced functionality.
6. Preload
As opposed to lazy loading, preloading is used to preload resources that will be accessed in the next page
Here are the preloaded types:
- Unconditional preloadingDownload something else as soon as the current page is loaded. For example, Google will download an Image Sprite that will be used in all results immediately after the page loads successfully.
- Conditional loading: Infer content to load based on user input, in yahoo’s case search.yahoo.com
- There is expected loading: This kind of situation usually occur in the web page to design, because users often visit the old page, the content of the page for the old local cache to adequately appear old web pages is very fast, and the new web content without caching, designers can pre-load some new in the old web content pages that may be used in content, so that a new page will be born to download resources.
7. Reduce DOM elements
Too many elements in a web page is a heavy burden to the page loading and script execution, 500 elements and 5000 elements can make a big difference in loading speed.
To find out how many elements are in your web page, you can calculate them with a simple command in your browser,
document.getElementsByTagName(‘*’).length
How much is too much? Yahoo said at the time of this writing that the home page had 700 + elements, but now it has nearly double that. At least we don’t have more web pages than Yahoo…
8. Classify content by domain name
Generally, the browser has a limit on the number of download connections in a domain. If you divide the download content by domain name, the browser can increase the number of parallel download connections. However, you should limit the number of domain names to two to four.
A typical site plan would place static resources like static.example.com and dynamic content at www.example.com. This also has the advantage of avoiding cookies on static domain names. We will mention this later in the cookie rule.
9. Reduce the number of IFrames
Understand the pros and cons of iframe when using iframe
Advantages:
- Can be used to load slower content, such as ads
- Safety sandbox protection. The browser controls the security of the content in the IFrame.
- Scripts can be downloaded in parallel
Disadvantages:
- Even iframe content that is empty consumes load time
- Prevents the page from loading
- No semantic
10. Avoid 404
404 we are familiar with, indicating that the server did not find the resource, we should pay special attention to the situation of 404 do not provide a web resource, the client sent a request but the server returned a useless result, time wasted.
To make matters worse, we need to load an external script on our web page, and the result is a 404, which not only blocks other script downloads, but the downloaded content (404) is parsed as Javascript by the client.
The CSS part
11. Avoid CSS expressions
CSS expressions can dynamically set CSS properties. They are supported in Internet Explorer 5 to Internet Explorer 8. Expressions are ignored in other browsers. For example, the following expression sets different background colors at different times.
background-color: expression( (new Date()).getHours()%2 ? "#B8D4FF" : "#F08A00" );
Copy the code
The problem with CSS expressions is that they are recalculated far more often than we think, not only when pages are drawn or resized, but also when scrolling or moving a mouse, so we try to avoid using them to avoid the performance penalty of using them incorrectly.
A similar effect can be achieved with a simple script
var currentTime = new Date().getHours();
if (currentTime%2) {
if (document.body) {
document.body.style.background = "#B8D4FF"; }}else {
if (document.body) {
document.body.style.background = "#F08A00"; }}Copy the code
12. Use @import instead
The reason to avoid @import is simple, as it is equivalent to placing CSS at the bottom of the web content.
13. Avoid using Filters
AlphaImageLoad is also supported in IE5.5-IE8. The use of this filter can cause images to block the rendering of web pages when downloading, and it can cause memory usage issues. It is no longer supported in IE9.
14. Put style sheets at the top
Placing a style sheet (CSS) in the HEAD of a web page makes the page appear to load faster because it allows the browser to progressively load the content of the page that is about to be downloaded. This is especially important for pages with lots of content, where users don’t have to wait on a blank screen to see what they’ve already downloaded.
If the style sheet is placed at the bottom, the browser will refuse to render the downloaded page, because most browsers try to avoid redrawing when implementing it. The content of the style sheet is the key information for drawing the page, and the viewer will have to be sorry before downloading it.
Javascript
15. Remove duplicate scripts
Repetitive scripts waste not only browser download time, but also parsing and execution time. A common way to avoid the introduction of duplicate scripts is to use a unified script management module, which not only avoids the introduction of duplicate scripts, but also allows for both script dependency management and version management.
16. Reduce DOM access
Access to DOM elements through Javascript is not as fast as we expect, especially for web pages with many elements. We should pay attention to Javascript access to DOM faster, and should:
- Caches already accessed elements
- Update the node “offline” and then add it back to the DOM Tree
- Avoid fixing layout problems with Javascript
17. Use intelligent event handling
Intelligent event handling requires a deeper understanding of event handling, different ways to fire as few events as possible, and early handling of events if necessary.
The page sometimes feels insensitive because there are too many frequently executing event handlers added to different elements of the DOM tree, which is why the use of event delegates is recommended. If you have 10 buttons in a div, you should only add one event handler to the div container, not one for each button. Events can bubble, so you can capture events and know which button is the event source.
18. Place the script at the bottom
The official HTTP/1.1 document recommends that browsers download no more than two files for each host name in parallel, or more than two files for images from multiple host names. If the script is being downloaded, the browser does not start any other downloading tasks, even if it is under a different host name. The browser parses and executes the script after it has been downloaded.
So for speeding up scripts, we can consider the following,
- Put the script at the bottom of the page so that the content needed for web rendering can be loaded and displayed to the user as quickly as possible.
- It is now supported by all major browsers
defer
Keyword to specify that the script should be executed after the document is loaded. - HTML5 is new
async
Keyword to allow the script to be executed asynchronously.
Use external Javascirpt and CSS files
Using external Javascript and CSS files allows these files to be cached by the browser and reused between different requests.
Changing Javascript and CSS from inline to External also reduces the size of web content.
The determining factor in using external Javascript and CSS files is the reuse rate of these external files, which can be a great benefit if users visit the same page multiple times while browsing our pages or can reuse different pages of scripts.
But for pages that users typically visit only once, such as the Front page of Microsoft.com, inline javascript and CSS can be relatively efficient.
Simplify Javascript and CSS
Streamlining means removing all whitespace and comments from Javascript or CSS,
body {
line-height: 1;
}
ol, ul {
list-style: none;
}
blockquote, q {
quotes: none;
}
Copy the code
Condensed version
body{line-height:1}ol,ul{list-style:none}blockquote,q{quotes:none}
Copy the code
Statistics show that the streamlined file size is reduced by an average of 21%, and even files with Gzip applied are reduced by 5%.
For example, I have 5 CSS and 4 Javascirpt on my site, and here are the results after Bundling and Minify respectively.
There is no processing before
After bundling Javascript and CSS
After simplifying Javascript and CSS
The picture
21. Optimize the image
Once the artist has finished the image design for the site, we can do the following to optimize the image before uploading it
-
Check that the number of image colors in the GIF image matches the palette specification. If you find that only 4 colors are used in the image and 256 color slots are displayed in the middle of the palette, then there is room for compression in the image.
This can be checked using imagemagick: identify -verbose image.gif
-
Try converting GIF to PNG to see if you save space. In most cases it is compressible.
GIF format can be safely converted to PNG format: convert image.gif image.png
-
Run PngCrush (or any other PNG optimization tool) on all PNG images.
For example, pngcrush image.png -rem alla-reduce-brute result.png
-
Run JPEGtran on all JPEG images. The tool can also be used to optimize and remove comments and other useless information from images
jpegtran -copy none -optimize -perfect src.jpg dest.jpg
22. Optimize CSS Sprite
- Sprite images arranged horizontally are generally smaller than vertical final files
- Groups of colors close together in Sprite can reduce the number of colors, ideally below 256 colors for the PNG8 format;
- Don’t leave large gaps between Sprite images. This does not increase the file size much, but it requires less memory for the user agent to decompress the image into a pixel map. A 100×100 picture is 10,000 pixels, and a 1000×1000 picture is a million pixels.
23. Do not zoom images in HTML
Don’t zoom in to fit the page, if you need small images, just use small images.
24. Use a small and cacheable favicon.ico
The site icon file favicon.ico, which browsers will try to request whether your server has it or not. So we want to make sure that this icon
- There are
- Keep the file size as small as possible, preferably less than 1K
- Set a long expiration time
cookie
25. Reduce Cookie size
Cookies are used for authentication or personalized Settings, and their information is contained in the HTTP header. For cookies, we should pay attention to the following points to improve the response speed of requests.
- Remove unnecessary cookies and completely ban pages that do not need cookies
- Reduce the size of cookies to a minimum
- Note the domain level of cookie Settings and do not affect other subdomains if necessary
- Set an appropriate expiration time. A long expiration time improves the response speed.
26. Use a cookie-free domain name for page content
Cookies are not necessary for the static resources of most websites. We can use different domains to store these static files separately, which can not only reduce the size of cookies and improve the response speed, but also has the advantage that some proxies refuse to cache the content with cookies. If we can remove these static resources cookies, Then you can get caching support for these proxies.
A common way to divide domain names is to place static files at static.example.com and dynamic content at www.example.com.
Some websites also need to apply cookies on the secondary domain name, and all subdomains will inherit. In this case, a special domain name will be purchased to store cookie-free static resources. Such as Yahoo! Yimg.com, YouTube ytimg.com, etc.
The mobile terminal
27. Keep individual contents smaller than 25KB
This is limited because on the iPhone, it can only cache less than 25K, note that this is the uncompressed size. So gzip alone may not be enough, thin file tools will be used.
28. Package and assemble compliance documents
Packaging page content into composite text is like Email with multiple attachments, which allows you to retrieve multiple components in a single HTTP request. When you use this rule, first determine if the user agent supports it (iPhone does not).
The server
29.Gzip compresses and transfers files
Gzip typically reduces the size of web content, including scripts, stylesheets, images, and more, by 70%. Gzip is more efficient than Deflate, and major servers have compression support modules.
It is worth noting that PDF files can be removed from the types that need to be compressed, because PDF files themselves are already compressed and gzip is not effective and wastes CPU.
30. Avoid the image SRC attribute being empty
Empty image SRC still causes the browser to send requests to the server, which is a complete waste of time and resources for the server. Especially if your site is visited by many people every day, the damage caused by empty requests can’t be ignored.
It comes in two main forms:
-
straight HTML
< img SRC = “” >
-
JavaScript
var img = newImage(); . Img SRC = "";Copy the code
31. The configuration ETags
Although the title is making ETags, you’ll need to make some situational judgments here. First, Etag is simply a file version identifier that makes it easy for the server to determine whether the content of the request has been updated, and if not, to reply 304 (not Modified) to avoid downloading the entire file.
However, the version information of Etags is not well supported across servers even by mainstream servers. For example, if you get Etags from one server in a cluster and then send them to another server, the verification is likely to fail.
32. Ajax requests using GET
Browsers implement XMLHttpRequest POST in two steps, sending the header first and then sending the data. GET, on the other hand, can complete the request with a TCP packet. In addition, semantically, GET is to fetch data from the server, while POST is to send data to the server, so we try to complete the data request through GET when using Ajax.
33. Flush early
In the web daemon we know of a method called response.flush (), which is usually called at the end of the program, but note that this method can be called multiple times. The purpose is to send the reply content in the existing cache to the client first, so that the client can “do something”.
So when is a good time to call this method? In general, we can call it once in advance when we need to load a large number of external scripts or stylesheets. The client receives a link to the script or other external resources and makes a parallel first request to download it. The server then sends the subsequent processing results to the client.
34. Use CDN (Content Delivery Network)
Once again, the first golden rule is to reduce the load time of web content. Increasing download speeds can also be improved through CDN(Content delivery Network). CDN improves download speeds for customers by deploying servers in different regions. If you have a lot of static content on your site that is accessed by people all over the world, then a CDN is essential. In fact, most of the Internet’s giants have their own CDNS. Our own website can distribute web resources through free CDN providers first.
35. Add Expires or Cache-Control headers
This rule falls into two parts:
- Add Expires to static content by setting it to never expire, or after a long time. Set Expires in IIS by configuring the HTTP Expires Response Header (IIS 7).
- Apply appropriate cache-control to dynamic content and let the browser send requests based on the criteria. For details about asp.net caching, see asp.net cache feature and asp.net caching best practices.
Refer to the link
- 【 Original 】 Yahoo front end optimization of 35 catch-22
- Front-end Performance Optimization —- Yahoo’s Front-end performance team summarized the 35 Golden Rules