Web page Front-End development optimization Reference list

Source: Internet
Author: User
Tags arrays constructor eval execution header include join variables

Web page Production WEBJX article introduction: Some experience summary of front-end development and optimization.

Found an article about front-end optimization , summary of a very comprehensive, to do everything difficult, often want to optimize and there is no time to optimize, like our company, a project linked to a project ~ new staff Training has been saved, but also want to optimize the front-end ah, but I really want to have the opportunity and the boss good integration of the company's website front-end code ~ But to the front-end optimization of the work in the usual writing code to go, it does not need to deliberately optimize the later. In the project development, backstage need to build a good frame, the front end is need to build a good frame, and in the page realization is realized, only in this way can be twice as much.

The previous period of time simple study of the next front-end optimization related knowledge, this article is a phased summary, or as an optimized reference list.

Objective

The front end is large, including HTML, CSS,Javascript,Image, Flash, and so on a variety of resources. Front-End optimization is complex, and there are different ways of doing it for every resource. So what is the purpose of the front-end optimization?

    1. From the user's point of view, optimization enables the page to load faster, respond more promptly to the user's actions, and provide users with a more user-friendly experience.
    2. From a service provider perspective, optimization can reduce the number of page requests, or reduce the bandwidth of the request, can save considerable resources.

In short, proper optimization not only improves the site's user experience but also saves considerable resource utilization.

There are many ways to optimize the front-end, according to the granularity can be divided into two categories, the first category is page level optimization, such as the number of HTTP requests, the script's non-blocking loading, the location optimization of the inline script, etc. the second category is code-level optimization, such as DOM operation optimization in Javascript , CSS selector optimization, picture optimization, and HTML structure optimization, and so on. In addition, in order to improve the input-output ratio, the various optimization strategies mentioned above are arranged roughly according to the input-output ratio from big to small.

First, page-level optimization


1. Reduce the number of HTTP requests

This strategy is generally known to all the front-end people, and is also the most important and effective. All said to reduce the HTTP request, the request is more what will happen? First, each request is cost-inclusive of both the time cost and the resource cost. A complete request requires a "lengthy" and complex process of DNS addressing, establishing a connection to the server, sending data, waiting for the server to respond, and receiving data. Time cost is the user needs to see or "feel" to this resource is must wait for the process to end, the resource because each request needs to carry data, so each request needs to occupy bandwidth. In addition, because the browser to make concurrent requests of the number of requests is a limit (see here ), so many requests after the browser needs to request in batches, so will increase the user's waiting time, will give users a slow site speed such an impression, The browser's progress bar persists even though the first screen of resources that may be visible to the user has been requested.

The main ways to reduce the number of HTTP requests include:

(1). Simplify the page from the design implementation level

If your page is as simple as Baidu homepage, then the next rule is basically unnecessary. It is most straightforward to keep the pages simple and reduce the use of resources. If this is not the case, your page needs gorgeous skin, then continue reading the content below.

(2). Setting up the HTTP cache reasonably

The power of caching is powerful, and proper caching settings can greatly reduce HTTP requests. To have AH home For example, when the browser does not cache the access will send out 78 requests, a total of more than 600 K data (such as Figure 1.1), and when the second access is cached after the browser has only 10 requests, a total of 20 k data (such as Figure 1.2). (here needs to be explained, if the direct F5 refreshes the page the effect is different, in this case the request number still is same, but is cached the resource the request server is 304 response, only header has no body, may save the bandwidth)

As shown in Figure 1.1

As shown in Figure 1.2

What's the reasonable setting? The principle is very simple, can cache the more the better, can cache the longer the better. For example, a rarely changing picture resource can set a long expiration header directly through the expires in the HTTP header, and resources that vary infrequently and may change can use last-modifed to authenticate requests. As much as possible so that resources can stay in the cache longer. About the specific settings and principles of HTTP caching here is no longer detailed, interested can refer to the following articles:

Description of caching policies in the HTTP1.1 protocol

Introduction to Caching in Fiddler HTTP performance

(3). Resource Merging and compression

If possible, merge external scripts, styles, and more than one. In addition, CSS, Javascript, image can be used to compress the corresponding tools, compressed often can save a lot of space.

(4). CSS Sprites

Merging CSS Pictures is another good way to reduce the number of requests.

(5). Inline Images

Embedding a picture into a page or CSS using data: URL scheme is a good idea if you don't consider resource management issues. If it's an embedded page, it will increase the volume of the page, and it won't take advantage of the browser cache. It is more desirable to use a picture in CSS.

(6). Lazy Load Images

This strategy actually does not necessarily reduce the number of HTTP requests, but it can reduce the number of HTTP requests under certain conditions or when the page is just loaded. For a picture, you can load only the first screen when the page is loaded, and then load subsequent pictures when the user continues to roll the screen back. As a result, the remaining picture requests are saved if the user is interested in only the contents of the first screen. Yes, there is. Home used to be in the load when the first screen after the image address cached in the TEXTAREA tag, the user to roll down the screen when the "lazy" load.

2. Base the external script

As mentioned earlier, browsers can be requested concurrently, this feature makes it possible to load resources faster, while outside-chain scripts can block other resources while loading, such as pictures, styles, and other scripts that follow the script before it finishes loading, until the script is loaded. If you put the script in a relatively high position, it can affect the load speed of the entire page and thus affect the user experience. There are a number of ways to solve this problem, with a more detailed description here ( translation and a more detailed example ), and the simplest way to rely is to move the script as backward as possible to reduce the impact on concurrent downloads.

3. Execute inline Script asynchronously

The performance impact of the inline script is worse than the external script. Home, like an external script, the inline script blocks concurrent requests as it executes, and in addition, because browsers are single-threaded in page processing, the rendering of the page is deferred when the inline script is executed before the page renders. In short, the inline script is in a blank state when it executes. In view of the above two reasons, it is recommended that inline scripts with longer execution times be asynchronously executed asynchronously in many ways, such as using the defer attribute of the script element (there are compatibility issues and other issues, such as inability to use document.write), With settimeout, in addition, the mechanism of WEB workers introduced in HTML5 can precisely solve such problems.

4. Lazy Load Javascript

With the popularity of Javascript frameworks, more and more sites are using the framework. However, a framework often includes a number of functional implementations that are not required for every page, and if you download unwanted scripts, it is a waste of resources-both wasting bandwidth and wasting time on execution. There are probably two ways to do this, one for those pages that are particularly large in traffic, specifically for the mini version, and the other for lazy Load. Yui used the second way, in the Yui implementation, initially only loaded the core module, other modules can wait to use the time before loading.

5. Put the CSS in the head

If you put the CSS in other places such as body, then the browser may have not been downloaded and resolved to the CSS has begun to render the page, which causes the page from no CSS state jump to the CSS state, the user experience is worse. In addition, some browsers will be finished after the CSS download to start rendering the page, if the CSS placed in the lower position will cause the browser to delay rendering time.

6. Asynchronous Request callback

There may be such a requirement in some pages that you need to use a script tag to asynchronously request data. Similar:
Javascript:

function Mycallback (info) {
//do something here
}

Html

<script src= "HTTP://ABC.COM/CB" type= "Text/javascript" ></script>

What the callback returns:
myCallback("Hello world!");

Like the above way directly on the page to write <script> on the performance of the page is also influential, that is, increased the burden of the first load on the page, delayed the domloaded and Window.onload events triggered the time. If timeliness allows, consider loading when the domloaded event is triggered, or use the SetTimeout method to control the loading time flexibly.

7. Reduce unwanted HTTP Jumps

For HTTP links that are accessed as tables of contents, many people will ignore the link's last "/", and if your server treats it differently, you also need to be aware that it is possible to hide 301 jumps and add extra requests. See the figure below, where the first link is accessed at no '/' end, so the server has a jump.

Figure 1.3

8. Avoid duplicate requests for resources

This is mainly due to negligence or the fact that the page is spliced by multiple modules, and then the same resource is requested in each module, which results in a duplicate request for the resource. The probability of appearing is not big, but still must pay attention to the investigation, otherwise may appear the following situation, comes from here .

Figure 1.4

Figure 1.4, the same JS in a page requested 9 times, all 200 requests, of course, this is a relatively extreme situation.

Second, code-level optimization

1. Javascript

(1). DOM

Dom operations should be one of the most performance-consuming operations in a script, such as adding, modifying, deleting, or manipulating a DOM collection. If you have a large number of DOM operations included in your script, you need to be aware of the following points:

A. HTML Collection

In the script, Document.images, Document.forms, getElementsByTagName () return a collection of htmlcollection types that are used mostly as arrays when used in peacetime, Because it has a length property, you can also use an index to access each element. However, the access performance is much worse than the array, because the collection is not a static result, it represents only a specific query, each access to the collection will be executed again to update the query results. The so-called "Access Collection" includes reading the length property of the collection, and accessing the elements in the collection.

So, when you need to traverse the HTML collection, try to turn it into an array and then access it to improve performance. Even if you do not convert an array, try to access it as little as possible, for example, when traversing the length property, saving the member to a local variable, and then using a local variable.

B. Reflow & Repaint

In addition to the above, the DOM operation also needs to consider the browser's reflow and repaint, because these are the resources that need to be consumed, the specific can participate in the following article:

How to reduce the repaint and reflow of browsers?

Understanding Internet Explorer Rendering Behaviour

Notes on HTML reflow

(2). Careful use with

with(obj){ p = 1}; The behavior of the code block is actually to modify the execution environment in the code block, placing obj at the very front of its scope chain and accessing non-local variables in the with code block is the first to start looking from obj, and if no more is found by the scope chain in turn, the use of with is the equivalent of increasing the scope chain length. And each lookup scope chain consumes time, and too long scope chains can cause the lookup performance to drop.

Therefore, unless you are sure to access only the attributes in obj in the with code, use with, instead of the properties that you need to access by using the local variable cache.

(3). Avoid using eval and function

Each time the Eval or function constructor acts on the source code represented by the string, the scripting engine needs to convert the source to executable code. This is a very resource-intensive operation-usually 100 times times slower than a simple function call.

The Eval function is extremely inefficient, and because of the lack of prior knowledge of what is passed to the eval string, eval interprets the code to be processed in its context, meaning that the compiler cannot optimize the context, so only browsers can interpret the code at run time. This has a significant impact on performance.

The function constructor is slightly better than eval because using this code does not affect the surrounding code, but it is still slow.

In addition, using eval and function is not conducive to the JavaScript compression tool performing compression.

(4). Reduce scope Chain Lookup

This article discusses the scope chain lookup problem, which is especially important in the loop. If you need to access a variable in a loop that is not in this scope, cache the variable with a local variable before traversing it. And then rewrite that variable at the end of the traversal, which is especially important for global variables because the global variable is at the top of the scope chain and the number of lookups is the most when accessed.

The low efficiency of the wording:

global variable
var globalvar =
				1;
function Mycallback (info) {
for (
				var i =
				100000; i--;) {
//each visit Globalvar needs to find the top of the scope chain, which requires access 100,000 times in this case
Globalvar = i
}
}

More efficient wording:

global variable
var globalvar =
				1;
function Mycallback (info) {
//local variable cache global variable
var localvar = Globalvar;
for (
				var i =
				100000 i--;) {
//access local variable is the fastest
localvar = i;
}
In this case, you only need to access 2 times global variable
globalvar = Localvar;

In addition, the use of closures should also be reduced to reduce the scope chain lookup.

(5). Data access

Data access in JavaScript includes direct amounts (strings, regular expressions), variables, object properties, and arrays, where access to direct and local variables is the fastest, and more overhead for object properties and array access. It is recommended that the data be placed in local variables when the following conditions are present:

    1. Access to any object properties more than 1 times
    2. More than 1 accesses to any of the array members

In addition, you should minimize the search for objects and array depths as much as possible.

(6). String concatenation

Using the "+" number in JavaScript to stitch string efficiency is relatively low because each run will open up new memory and generate a new string variable, and then assign the concatenation result to the new variable. A more efficient approach than this is to use the array join method, where the string that needs to be spliced is placed in an array and the final call to its join method results. However, because the use of arrays also has some overhead, so you can consider this method when you need more strings for stitching.

For a more detailed description of JavaScript optimization, please refer to:

Write efficient Javascript (PPT)

Efficient JavaScript

2. CSS Selector

In most people's opinion, the browser's parsing of the CSS selector is done from left to right, for example

#toc A {
				color:
				#444;
				}

Such a selector, if it is from the right to the left parsing is very efficient, because the first ID selection will basically limit the scope of the lookup, but in fact the browser to the selector parsing is from right to left. As the above selector, the browser must traverse the ancestor node to find each a tag, and the efficiency is not as high as previously thought. According to this line of browser features, in the writing selector need to pay attention to a lot of things, someone has enumerated, details reference here .

3. HTML

The optimization of the HTML itself is now becoming more and more popular, and details can be found in this concluding article .

4. Image compression

Picture compression is a technical work, but now this aspect of the tool is also very much, compression can often bring good results, the specific compression principles and methods in the "even faster Web Sites" 10th chapter has a very detailed introduction, interested can go to see.

Summarize

This article from the page level and the code level two granularity to the front-end optimization of various ways to do a summary, these methods are basically front-end developers in the development process can be used for reference and practice, in addition, complete front-end optimization should also include many other ways, such as CDN, Gzip, Multi-domain name, no cookie server and so on, because of the operability of the developer is not strong, there is no more narrative, the detailed reference to Yahoo and Google these "golden rules."

Original link: http://varnow.org/?p=260



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.