Introduction
The high-performance part of the front-end mainly refers to reducing the number of requests, reducing transmitted data, and improving user experience. In this part, image optimization is crucial. The beautification of many websites is achieved by beautiful pictures, which are precisely the culprit of bandwidth usage. For each IMG tag, the browser tries to initiate a download request. This article describes several image optimization methods in detail, describes the tools used and the results after optimization.
Image Compression
Reducing the image size can significantly improve the performance. For existing images, to reduce the image size, you can only change the image format. Here we recommend the png8 format, it can reduce the image size while maintaining the definition. After knowing this principle, you can use the drawing tools of windows and the Photoshop tools to change them one by one. However, the disadvantage of doing so is that the processing efficiency is too slow. This article recommends an online Conversion Tool smush. it, which can be compressed and converted in batches. Its address is www.smushit.com/ysmush.it. Shows the effect after opening.
Figure 1. Online compression tool provided by Yahoo
We uploaded a 3790 K image to be online.ProgramAfter processing, click Download smushed images to download and view the result. Shows the download interface.
Figure 2. Compressed results
Open the downloaded package and check the result. The image size is reduced from 3790 to 3344, as shown in. For a large number of image websites, this method helps to quickly compress images in batches.
Figure 3. Compressed results
Image merging to Implement CSS Sprites
CSS Sprites is an attractive technology. It is actually to integrate some background images in a webpage into an image file, and then reuse CSS
"Background-image", "Background-
Repeat "," Background-Position "combination for background positioning, background-Position
You can use numbers to precisely locate the background image. CSS Sprites can effectively reduce HTTP requests of webpages, greatly improving the page performance.
The biggest advantage of CSS Sprites is its widespread spread and application. CSS Sprites
This can reduce the size of the image. Because the basic information does not need to be duplicated after the image is merged, the size of the bytes that multiple images are merged into one image is always smaller than the total size of these images. Meanwhile, CSS
Sprites
It solves the problem of webpage designers naming pictures. You only need to name a set of images without naming every small element, thus improving the webpage production efficiency. Easy to change style, only
You need to modify the color or style of an image on one or more images. The style of the entire webpage can be changed. It is easier to maintain. At the same time, because the image is merged into an image, the number of requests for the image is reduced.
To 1. Other requests can be cached locally without accessing the server. Is a merged image. It brings together many small icons.
Figure 4. merged image
Here is a small tool named "CSS Sprites style generation tool 2.0", which can be downloaded from here. This is a simple and free tool. Use this tool to open the image above and select a part of the image. For example, in the "Green Thumb" section, the tool calculates the length, width, and distance from the upper left corner. Select the copy class name, copy width, and copy height, and then click "Copy current style. The generated style is copied to the clipboard.
Figure 5. Use of gadgets
Generated CSSCodeAs shown in Listing 1.
Listing 1. CSS code generated by the gadgets
. Div_6148 {width: 18px; Height: 20px; Background-position:-17px-209px ;} |
Use this code on the webpage. Its code is shown in the following list.
Listing 2. Test the CSS Sprites code
Shows the result of opening the test page.
Figure 6. Test the webpage Effect
You can see that only the "Green Thumb" part selected by the tool is displayed on the webpage. Such code can be used in multiple parts of the webpage, and the image only needs to be downloaded once, this is the biggest advantage of this technology, reducing the number of requests caused by small images.
Multi-domain request
Sometimes, there is too much image data. Some companies can resolve this issue by assigning image data to servers with multiple domain names. In this case, requests from servers are distributed to multiple hardware servers. Another
The browser features are used. Generally, browsers use up to 2-4 images with the same domain name.
Parallel download by threads. The number of concurrent downloads varies with browsers, as shown in the following list.
Listing 3. Concurrent downloads of various browsers
Browsers HTTP/1.1 HTTP/1.0 IE6, 7 2 4 IE8 6 6 Firefox 2 2 2 8 Firefox 3 6 6 Safari 4 4 4 chrome? Chrome 3 4 4 Opera 9.63, 10.00 Alpha 4 4 4 |
For other images with the same domain name, the download starts only after the other images are downloaded. Here I did a test and selected multiple images with the same domain name on the same webpage. The code is shown in listing 5.
Listing 4. Multi-image download for a Single Domain Name
<HTML> <body> <br> <br> <br> <br> <br> </body> |
Next, use the firebug plug-in of Firefox to monitor the network. Shows the result.
Figure 7. Monitoring results of multiple images for a Single Domain Name
As you can see, the download start point of multiple images with the same domain name is delayed. They are not parallel downloads. When we replace the three images with other domain name images. As shown in Listing 6.
Listing 5. multi-domain and multi-image download
<HTML> <body> <br> <br> <br> <br> <br> </body> |
View the network monitoring again and you can see that these images are downloaded in parallel.
Figure 8. multi-domain name multi-image test results
The download of multiple domain names is good, but too many domain names are not very good. Generally, the download of 2-3 domain names is similar.
Base64 encoding of the image
In any case, image download requests must always be sent to the server. If the image download does not need to be sent to the server, but can be downloaded to the local device at the same time as the HTML download. Currently, the browser supports this feature. We can encode the image data into a base64 string and use this string to replace the image address. HypothesisSIndicates the base64 string, you can use S"> To display this image. We can see that the image data is included in the HTML code, and there is no need to access the server again. How can an image be encoded as a base64 string? You can use the online tool "base64 online" to upload images and convert them to base64 strings. Of course, if you are interested, you can implement a base64 encoding tool by yourself. For example, if you use Java for development, its code is shown in listing 7.
Listing 6. base64 Java code
Public static string getpicbase64 (string picpath) {string content = NULL; try {fileinputstream FCM = new fileinputstream (picpath); byte [] bytes = new byte [FCM. available ()]; FCM. read (bytes); content = new sun. misc. base64encoder (). encode (bytes); // The specific encoding method. close ();} catch (exception e) {e. printstacktrace ();} return content ;} |
This article encodes an image and writes the encoded base64 string to HTML, as shown in listing 8.
Listing 7. Test HTML code embedded with base64
Because the image data is contained in a base64 string, you do not need to request image data from the server, as shown in.
Figure 9. base64 display image
However, this policy cannot be abused. It applies to the time when the browser connects to the server>
The image download time, that is, the cost of initiating a connection is greater than the image download time. In this case, the image is encoded as base64.
To avoid connection establishment and improve efficiency. If the image is large, use base64
Encoding can avoid connection establishment, but the request establishment only accounts for a small proportion of the image download.
Base64: The image cache will become invalid for dynamic web pages (static Web pages can be cached), and base64
The total size of the string must be greater than the size of the pure image, which is very inappropriate. Therefore, if your page is already static and the image is not very large, try base64
Encoding. The client caches the webpage content and the base64 encoding of the image. If your page is a dynamic page, the image is large.
String, so the image cannot be base64 encoded, and the image is referenced normally, so that the image is cached in the browser to improve the download speed. From the perspective of reality, such as online
The small icons in the HTML editor, such as smiling faces, all use base64 encoding, because they are very small, many, base64
This helps reduce the number of icon requests on webpages and improve efficiency.
Gzip Compression
Compression is a good choice to reduce the amount of data transmitted. Http supports gzip compression formats, and the server response header contains
Content-encoding: gzip, which tells the browser that the returned data of this response has been compressed into Gzip
Format. After the browser obtains the data, it needs to decompress it. This can reduce the data transmitted by the server to a certain extent and improve the system performance. How to add a response to the server
Content-encoding: gzip header, which compresses response data at the same time? If you are using a Tomcat server, open
$ Atat_home $/CONF/server. xml file to configure ctor, as shown in listing 9.
Listing 8. tomcat configuration list
<Connector Port = "80" maxhttpheadersize = "8192" maxthreads = "150" minsparethreads = "25" maxsparethreads = "75" enablelookups = "false" redirectport = "8443" acceptcount =" 100 "connectiontimeout =" 20000 "disableuploadtimeout =" true "uriencoding =" UTF-8 "compression =" on "compressionminsize =" 2048 "nocompressionuseragents =" gozilla, traviata "compressablemimetype =" text/html, text/XML "/> |
We have added the following attributes for ctor:
Compression = "on" enable the compression function
Compressionminsize = "2048" enables the size of compressed output content. The default value is 2 kb.
Nocompressionuseragents = "gozilla, Traviata" does not enable compression for the following browsers:
Compressablemimetype = "text/html, text/XML, image/PNG" compression type
Sometimes, we cannot configure Server. xml. For example, if we only rent other people's space but it does not enable gzip, we need to use the program to enable the gzip function. We put the files to be compressed into the specified folder and use a filter to filter requests for the files in this folder.
Listing 9. Custom filter compression Gzip
// Monitor the gzipcategory folder request @ webfilter (urlpatterns = {"/gzipcategory/*"}) public class gzipfilter implements filter {@ override public void dofilter (servletrequest request, servletresponse response, filterchain chain) throws ioexception, servletexception {string parameter = request. getparameter ("gzip"); // determines whether the accept-encoding request header is included in httpservletrequest S = (httpservletrequest) request; string hea Der = S. getheader ("Accept-encoding"); // "1 ". equals (parameter) is only used for control. If gzip = 1 is input, compression is performed. The purpose is to test if ("1 ". equals (parameter) & header! = NULL & header. tolowercase (). contains ("gzip") {httpservletresponse resp = (httpservletresponse) response; Final bytearrayoutputstream buffer = new bytearrayoutputstream (); required hsrw = new callback (RESP) {@ override public printwriter getwriter () throws ioexception {return New printwriter (New outputstreamwriter (buffer, getcharacterencoding ();} @ overri De public servletoutputstream getoutputstream () throws ioexception {return New servletoutputstream () {@ override public void write (int B) throws ioexception {buffer. write (B) ;}}}}; chain. dofilter (request, hsrw); byte [] gzipdata = gzip (buffer. tobytearray (); resp. addheader ("content-encoding", "gzip"); resp. setcontentlength (gzipdata. length); servletoutputstream output = response. getoutputstrea M (); output. write (gzipdata); output. flush ();} else {chain. dofilter (request, response) ;}// use gzip to compress the byte array private byte [] gzip (byte [] data) {bytearrayoutputstream byteoutput = new bytearrayoutputstream (10240 ); gzipoutputstream output = NULL; try {output = new gzipoutputstream (byteoutput); output. write (data);} catch (ioexception e) {} finally {try {output. close ();} catch (ioexception e ){} Return byteoutput. tobytearray ();}......} |
The main idea of this program is to perform gzip compression on the Response byte data before the response stream is written back, because not all browsers support gzip decompression. If the browser supports gzip decompression, gzip is included in the accept-encoding of the request header. This indicates that the server browser supports gzip decompression. Therefore, if the program is used to control the compression, you must determine whether the browser sends the accept-encoding: gzip header. If this header is included, to perform compression. To verify before and after compression, use firebug to monitor request and response headers.
Listing 10. Request before compression
GET/testproject/gzipcategory/test.html HTTP/1.1 accept: */* accept-language: ZH-CN accept-encoding: gzip, deflate User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; sv1) Host: localhost: 9090 connection: keep-alive |
Listing 11. uncompress response
HTTP/1.1 200 OK server: APACHE-Coyote/1.1 etag: W/"5060-1242444154000" last-modified: sat, 16 May 2009 03:22:34 GMT Content-Type: text/htmlContent-Length: 5060Date: Mon, 18 May 2009 12:29:49 GMT |
Listing 12. Compressed response
HTTP/1.1 200 OK server: APACHE-Coyote/1.1 etag: W/"5060-1242444154000" last-modified: sat, 16 May 2009 03:22:34 GMTContent-encoding: GzipContent-Type: text/htmlContent-Length: 837Date: Mon, 18 May 2009 12:27:33 GMT |
We can see that the compressed data is much smaller than the data before compression. The compressed response header contains content-encoding: gzip. Content-Length also contains the size of the returned data. Gzip compression is an important feature. we mentioned earlier that it is optimized for compression on a single server. In the case of high concurrency, reverse proxy technology is required before multiple Tomcat servers, improve the concurrency, while the currently popular reverse proxy is nginx (this is in the futureArticleWill be detailed ). Add the following configuration to the HTTP configuration section of nginx.
Listing 13. gzip configuration of nginx
Gzip on; gzip_min_length 1000; gzip_buffers 4 8 K; gzip_types text/plain application/X-JavaScript text/CSS text/HTML Application/XML; |
Because nginx has higher performance, this configuration can better improve performance. This configuration can be very useful on high-performance servers.
Lazy loading and pre-loading
Pre-loading and lazy loading are policies to improve user experience. They do not actually improve program performance, but can significantly improve user experience or reduce server pressure.
The principle of pre-loading is to download the next image to the local device when you view it. When you actually access the next image, you do not need to download data from the server to improve the user experience. To implement pre-loading, we can implement the following function.
Listing 14. pre-loaded Functions
Function preload (callback) {var imageobj = new image (); images = new array (); images [0] = "pre_image1.jpg"; images [1] = "pre_image2.jpg "; images [2] = "pre_image3.jpg"; for (VAR I = 0; I <= 2; I ++) {imageobj. src = images [I]; If (imageobj. complete) {// if the image already exists in the browser cache, call the callback function callback directly. call (imageobj);} else {imageobj. onload = function () {// call the callback function asynchronously when the image download is complete. call (imageobj); // replace this of the callback function with the image object };}} function callback () {alert (this. SRC + "loaded, you can continue to pre-load the next group of images here ");} |
The code above defines the image object, declares the Image array to be preloaded, and starts loading (. src = images [I]) one by one. If it is already in the cache, no other processing will be performed. If it is not in the cache, It listens to the onload event and will be called when the image is loaded.
In contrast, lazy loading is performed when the user needs it. A web page may contain hundreds of images at the same time. In most cases, users only view a portion of the images. If hundreds of images are displayed at the same time, a large amount of bandwidth resources are wasted, therefore, when you pull down the scroll bar, you can request to download the image to be viewed. This principle is similar to the word display policy.
In JavaScript, the basic principle is to first have a container object, which contains an IMG element set. Use a method such as hide or replace to stop IMG loading, that is, to stop it from downloading images. Then, the IMG element is displayed. When the element is within the loading range, it is loaded (that is, the IMG label is displayed or inserted ). The loading range is generally the container's visual range, that is, within the viewer's visual range. When the container rolls or the size changes, the elements are re-checked. This is repeated until all elements are loaded. For Development, choosing an existing mature component is a best practice. lazy load plugin for jquery is a jquery-based lazy load component that has its own official website. This is a good free plug-in. It can help programmers quickly develop and load applications on a lazy basis.
Summary
This article summarizes several methods for high-performance optimization of front-end images. When necessary, you can view the content of this article, it can help readers optimize the performance of the front end. I will continue to write the subsequent sections, including database optimization, Server Load balancer, and reverse proxy. This includes my limited level. If you have any mistakes, please contact me for criticism and correction.
In the second part, I will introduce the front-end bigpipe technology, flush mechanism, dynamic/static separation, HTTP persistent connections, flexible HTTP application, static and pseudo static, and page cache (overall and partial, and apply them to Java Web development. These technologies can help improve the performance of Java Web applications.