Web Front End performance optimization

Source: Internet
Author: User
Tags domain name server website performance

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

1 @import url("style.css")

It is recommended that you use the following code instead.

1 <linkrel="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:

1 document.write(‘<script src="another.js"></script>‘);

Suggested changes to:

1 <scriptsrc="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. Using CSS sprites to integrate images

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.

12 .megaphone {width:50px; height:50px; background:url(images/sprite.png) 00px;}.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.

123456789101112 <script type="text/javascript">functiondownloadJSAtOnload() {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);elsewindow.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.

1234567 <styletype="text/css"><!--CSS代码--></style> <scripttype="text/javascript"><!--JavaScript代码--></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:

123456789 body{background-color:#d0e4fe;}h1{color:orange;text-align:center;}

After compression:

12 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.

12345678910 <head><metaname=description content="description"/><title>title</title><style>page specific css code goes here</style><scripttype="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.

Related Article

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.