A collection of best practices and tools for Web front-end optimization published in2013-09-23 19:47| 21,315 Reads | source Googe & yahoo| 118 Comment | author wangguo compilation Web optimization Google Yahoo pagespeedyslow
Summary:The performance of the front end is important for the user experience of the Web App. Don't assume that your web app is good enough, but there are plenty of things you can do to improve your performance. This article introduces Google and Yahoo! Best practices and tools for front-end optimization, and you can test your web app one by one.
The performance of the front end is important for a Web application, and if a Web application's page loads very quickly and responds to the user's actions in a timely manner, the product's user experience will be greatly improved. Shows how the page load speed affects the user experience.
Is your Web page fast enough? In fact, there may be many places to ascend. Google and Yahoo have also proposed some front-end optimizations for Web apps and released tools that you can examine your Web application to achieve higher performance.
These optimizations not only provide a better experience for the user, but also, from a developer perspective, can reduce the number of requests to the page, reduce the bandwidth of requests, and reduce the waste of resources.
Here's a look at the best Practices for Web page optimization offered by Google and Yahoo.
first, Google's best practices for Web optimization
1. Avoid bad requests
Sometimes the HTML or CSS in the page asks the server for a non-existent resource, a slice or HTML file, which causes too many round trips between the browser and the server, similar to the following:
- Browser: "I need this image." ”
- Server: "I don't have this image. ”
- Browser: "Are you sure?" This document says you have. ”
- Server: "No, really." ”
This will slow down the loading of the page. Therefore, checking the page for bad links is very necessary, you can use Google's Pagespeed tool to detect, find a problem, add the appropriate resource files or modify the resource's link address.
2. Avoid Css@import
Referencing a CSS file using the @import method can lead to some problems affecting the speed of the page loading, such as causing the file to load sequentially (one loaded before the other is loaded), and cannot be loaded in parallel.
You can use the CSS delivery tool to detect whether the @import method exists in the page code. For example, if the test result exists
[CSS]View Plaincopy
- @import url ("style.css")
It is recommended that you use the following code instead.
[HTML]View Plaincopy
- <link rel="style.css" href="style.css" type= "text/css">
3. Avoid using document.write
In JavaScript, you can use document.write to display content on a Web page or to invoke external resources, and in this way the browser has to take some extra steps--download resources, read resources, run JavaScript to understand what needs to be done, This process needs to be re-executed once other resources are called. Because the browser does not know what to display before, it slows down the page load.
You know, any resource that can be called by document.write can be called through HTML, which is faster. Check your page code if there is a code similar to the following:
[JS]View Plaincopy
- document.write (' <script src= ' another.js ' ></script> ');
Suggested changes to:
[HTML]View Plaincopy
- <script src="Another.js"></script>
4. Merging multiple external CSS files
Every time you use a CSS file in your website, your page will load a little bit slower. If you have more than one CSS file, you should merge them into a single file.
You can use the CSS Delivery tool to detect CSS files in the page code and then merge them into one by copying and pasting them. After merging, remember to modify the reference code in the page and delete the old reference code.
5. Merging multiple external JavaScript files
In most cases, the Web site will often contain several JavaScript files, but it is not necessary to separate the files, some of which can be merged into one file.
You can use the Resource Check tool to detect the number of JavaScript files referenced in the page, and then you can merge multiple files into one by copying and pasting them.
6. Integrate images with Csssprites
If there are 6 small images on the page, the browser will be downloaded separately when displayed. You can combine these images into 1 through CSS sprites to reduce the time it takes to load a page.
CSS sprites requires two steps: Integrate the image and position the image. For example, you can use the following code to locate the upper and lower parts of the image below.
[CSS]View Plaincopy
- . Megaphone {width:50px; height:50px; background:URL (images/sprite.png) 0 0px;}
- . Smile {width:50px; height:50px; background:URL (images/sprite.png) 0 -50px;}
7. Delaying the loading of JavaScript
When the browser executes the JavaScript code, it stops processing the page and causes a serious delay when there are many JavaScript files or code to load on the page. Although you can delay the loading of JavaScript by using defer, async, or putting JavaScript code at the bottom of the page, these are not a good solution.
Here's what Google is suggesting.
[JS]View Plaincopy
- <script type="Text/javascript" >
- function Downloadjsatonload () {
- var element = document.createelement ("script");
- ELEMENT.SRC = "Defer.js";
- Document.body.appendChild (Element);
- }
- if (Window.addeventlistener)
- Window.addeventlistener ("Load", Downloadjsatonload, false);
- else if (window.attachevent)
- Window.attachevent ("onload", downloadjsatonload);
- else window.onload = downloadjsatonload;
- </script>
This code means waiting for the page to load and then loading the external "defer.js" file. Here are the test results.
8. Enable Compression/gzip
compressing HTML and CSS files using gzip typically saves about 50% to 70% of the size, so loading a page requires less bandwidth and less time.
You can use this gzip compression tool to detect if the page has been gzip compressed.
9. Enable Keep-alive
The HTTP protocol uses "request-answer" mode, when using normal mode (non-keepalive mode), each request/reply client and server will create a new connection, disconnect immediately after completion (the HTTP protocol is a non-connected protocol); Keep-alive mode (also known as persistent connection, connection reuse), the Keep-alive feature keeps the client-to-server connection active, and keep-alive functionality avoids establishing or re-establishing a connection when a subsequent request to the server occurs.
In HTTP 1.0 keep-alive is turned off by default, you need to add "connection:keep-alive" in the HTTP header to enable keep-alive, keep-alive by default in HTTP1.1, add " Connection:close "can be turned off. Most browsers now use the HTTP 1.1 protocol, which means that the Keep-alive connection request is initiated by default, so whether a full keep-alive connection can be completed depends on the setting of the Web server.
10. Embed small CSS and JavaScript code into HTML
If your CSS code is small, you can put this part of the code in an HTML file instead of an external CSS file, which can reduce the number of files required for page loading, thus speeding up the loading of the page. Also, you can embed small JavaScript script code in an HTML file.
[HTML]View Plaincopy
- <style type="Text/css">
- <!--CSS code--
- </style>
- <script type="Text/javascript">
- <!--JavaScript code--
- </Script>
11. Using Browser caching
When the page is displayed, the browser needs to load logos, CSS files, and other resources. The job of the browser cache is to "remember" the resources that have been loaded, making the page load faster.
12. Compressing CSS code
No matter how you use the Css,css file on the page, the smaller the better, this will help you to increase the speed of the page loading. You can compress your CSS code using the minify CSS tool.
Before compression:
[CSS]View Plaincopy
- Body
- {
- Background-color:#d0e4fe;
- }
- H1
- {
- Color:orange;
- Text-align:Center;
- }
After compression:
[CSS]View Plaincopy
- Body {background-color:#d0e4fe;}
- H1 {color:orange; Text-align:Center;}
13. Minimize the number of DNS queries
When a browser establishes a connection to a Web server, it needs to resolve the DNS to resolve the domain name to an IP address. However, once the client needs to perform DNS lookup, the wait time will depend on the speed of the domain name server's effective response.
Although all ISPs ' DNS servers can cache domain names and IP address mapping tables, if the cached DNS records expire and need to be updated, it may be necessary to traverse multiple DNS nodes, sometimes requiring a global scope to find a trusted domain name server. Once the domain name server is busy and the request is resolved in a queue, the wait time is further delayed.
Therefore, it is important to reduce the number of queries for DNS, and to avoid additional time-consuming when pages are loaded. To reduce the number of DNS queries, the best solution is to reduce the chance of different domain name requests on the page.
You can use the Request Checker tool to detect how many requests exist on the page and then optimize them.
14. Minimize redirects
Sometimes you need to use redirects in your Web pages for specific needs. Redirection means that the user's original request (for example, request a) is redirected to another request (for example, request B).
But this can cause the website performance and the speed to descend, because the browser accesses the URL is a series of process, if accesses halfway and jumps to the new address, will repeatedly initiate a series of processes, this will waste a lot of time. So we try to avoid redirects, Google recommends:
- Do not link to a page that contains redirects
- Do not request resources that contain redirects
15. Optimize the order of style sheets and scripts
The style label and style sheet call code should be placed in front of the JavaScript code, which can make the page load faster.
[HTML]View Plaincopy
- <head>
- <meta name=description content="description"/>
- <title>title</title>
- <style>
- Page specific CSS code goes here
- </style>
- <script type="Text/javascript">
- JavaScript code goes here
- </Script>
- </head>
16. Avoid javascripts blocking rendering
When the browser encounters a <script> tag that introduces an external JS file, it stops all work to download and parse it, and in the process, page rendering and user interaction are completely blocked. When the page loads, it will stop.
Google recommends removing the JavaScript that is loaded on the first screen of the interfering page, which is the page that the user initially sees on the screen, whether it is a desktop browser, a mobile phone, or a tablet computer.
17. Reduce the original image
If you do not need to display large images in the page, it is recommended to reduce the actual size of the image to the size shown, which reduces the time required to download the image.
18. Specify the image size
When the browser loads the HTML code of the page, it is sometimes necessary to position the page layout before the picture is downloaded. If the image in the HTML does not specify a size (width and height), or if the size of the code is not the size of the actual picture, the browser will "backtrack" the image and re-display it after the picture is downloaded, which consumes extra time.
So, it's a good idea to specify dimensions for each picture in the page, whether it's in the tab in HTML or in CSS.
More information: https://developers.google.com/speed/docs/insights/rules
Second, Yahoo's web optimization best Practices
1. Content Optimization
- Minimizing HTTP requests: Common methods include merging multiple CSS files and JavaScript files, using CSS sprites to integrate images, image map (different areas of the image with different links), inline images (using Data:url scheme Embedded image data in the actual page).
- Reduce DNS Lookups
- Avoid redirects
- To make Ajax cacheable
- Lazy Load Component: Consider what content is required to be loaded first, what content and structure can be loaded at a later time, and set according to that priority.
- Preloaded components: Pre-loading is the page content (like, style sheets, and scripts) that can be requested in the future when the browser is idle. When the user wants to access the next page, most of the content in the page has been loaded into the cache, so the access speed can be greatly improved.
- Reducing the number of DOM elements: there are a large number of DOM elements in the page that can cause JavaScript to traverse the DOM more efficiently.
- Divide page content by domain name: dividing the page content into sections allows you to maximize parallel downloads. But make sure you're using a domain number between 2 and 4 (otherwise conflict with 2nd).
- Minimizing the number of IFRAME: IFRAMEs provides an easy way to embed the content of a site into another site. But it is created 1-2 times slower than other DOM elements, including JavaScript and CSS.
- It is not necessary to avoid 404:http request time consumption, so it is completely unnecessary to use an HTTP request to get a useless response (for example, 404 does not find a page), it will only degrade the user experience without a little benefit.
2. Server Optimization
- Use a Content distribution network (CDN): Spread your site content across multiple, geographically located servers to speed download speeds.
- Add expires or Cache-control information header: For static content, you can set the file header expiration time expires value of "never expire (never expires)"; For dynamic content, You can use the appropriate Cache-control file header to help your browser make a conditional request.
- gzip compression
- Setting Etag:etags (Entity tags, entities tags) is a mechanism that Web servers and browsers use to determine whether content in the browser cache matches the original content in the server.
- Flush buffers Early: When a user requests a page, the server spends 200 to 500 milliseconds to organize the HTML file in the background. During this time, the browser will remain idle for data return. In PHP, you can use the flush () method, which allows you to send a well-compiled partial HTML response file to the browser first, and the browser can download the contents of the file (script, etc.) while processing the remaining HTML pages in the background.
- Use the Get method for Ajax requests: When using XMLHttpRequest, the Post method in the browser sends the file header before the data is sent. So using get is the most appropriate.
- Avoid empty image src
3. Cookie optimization
- Reduce cookie size: Remove unnecessary coockie and make the Coockie volume as small as possible to reduce the impact on user response
- Use domain name-independent cookies for Web Components: cookie reading of static components is a waste, a good way to store static components with another cookie-free domain name, or you can store only domain names with www in a cookie.
4. CSS Optimization
- Put CSS code at the top of the HTML page
- Avoid using CSS expressions: CSS expressions are computationally large at execution time and can have a big impact on page performance
- Use <link> to replace @import
- Avoid using the Filters:ie exclusive property alphaimageloader to correct the translucent effect of PNG images in IE 7, but the problem is that when the browser loads the picture it terminates the rendering of the content and freezes the browser.
5. JavaScript optimization
- Place JavaScript scripts at the bottom of the page
- referencing JavaScript and CSS as external files: using external files in real-world applications can improve page speed because both JavaScript and CSS files can generate caches in the browser.
- Zoom out on JavaScript and CSS
- Delete duplicate scripts
- Minimizing access to the DOM: using JavaScript to access DOM elements is relatively slow
- Develop an intelligent event handler
6. Image Optimization
- Optimize picture size
- Optimize your pictures with CSS sprites
- Do not use the zoom picture in HTML
- Favicon.ico is small and cacheable
7. For mobile optimization
- Keep the component size below 25KB: mainly because the iphone cannot cache files larger than 25K (note that this refers to the uncompressed size).
- Package a component as a compound document: wrapping the page content into compound text is like an email with multiple attachments, which enables you to get multiple components in an HTTP request.
More information: http://developer.yahoo.com/performance/rules.html (Chinese translation)
third, some tools
1. Google pagespeed
Google offers the Pagespeed tool, a browser plugin that can be used to best apply the Web optimization practices mentioned by Google above – to help you easily analyze your site's performance bottlenecks and provide you with recommendations for optimization.
- Online Analysis of your website
- Install browser plugin (Chrome, Firefox)
- Embed Pagespeed functionality in your app with the Insights API
2. Yahoo YSlow
YSlow is a browser plugin that Yahoo has launched to help you analyze your site's pages and provide you with some optimization suggestions to improve the performance of your site.
- Firefox plugin
- Chrome Plugin
- YSlow for Mobile/bookmarklet
- Source
3. Other analysis optimization tools
- Spider Simulator: This tool can analyze your page and provide some suggestions for optimization.
- Image SEO Tool: This tool can check the ALT tag of the picture and provide some suggestions for optimization.
- Request Checker: Find out which resources and services you need to load on the page.
- Link checker: Check for internal, external, and invalid links on the page.
- HTTP Header check: Displays the HTTP response header for a Web page or resource.
- Social Checker: Check the social components on the page, such as Google +, Facebook, Twitter, LinkedIn, and Pinterest.
- If Modified Checker: Check if the page accepts if-modified-since HTTP headers.
- Gzip Checker: Check if the page has been gzip compressed.
- CSS Delivery tool: Check the CSS file used in the page.
- Breadcrumbs Tool: Provides breadcrumb navigation code based on the information you enter.
- CSS compression tool: Used to compress CSS code.
With the above optimization recommendations and optimization tools, you can easily find the bottlenecks that affect your Web page performance and easily improve the performance of your Web pages. If you also have experience in Web optimization, welcome to share.
Web front end optimization best practices and tools highlights