Website Design Front Introduction Series (i): the front-end various optimization

Source: Internet
Author: User
Keywords Slightly series before end attack

Intermediary transaction SEO diagnosis Taobao guest Cloud host technology Hall

Still have one hours to 2012, that still have a little time to write a bit of spit things, hehe ... December 2011 is definitely my work since the maximum pressure of one months, has been busy to sleep less time, part-time reading less time, the body began to alarm, shoulder responsibility pressure I really breathless ... As an ordinary north drift, in Beijing similar to me such a sea of humanity, especially in our industry.

I love life very much, every minute is precious, I love what I do now, even if it really makes me feel exhausted (so blogging is temporarily a method of decompression for me).

It seems to me that life is supposed to be like this, and since we choose a survival model or a difficult pattern in reincarnation, no matter what the difficulty is expected. So I am not here to express my complaints, but to remind myself and everyone "again busy and tired also don't forget their dreams and goals."

I suddenly think of an example of the Super Mary (Mario) that we should have played. No matter how many lives you have, it is a cloud, in the game you will encounter countless enemies (turtles, flying fish, cannibal flowers ...), encountered countless hardships (one after another pit, sewer, fire ...), but want to pass only one way, that is to save the princess, this is the goal.

  

If you are want to live a happy life, tie it to a goal. Not to arranges or things.

If you want to be happy, combine life with goals, not from others or from matter.

A long time to come out to take a bubble, so it is inevitable to spit slot, do not like the above paragraph as a lively, below we start the topic.

As my 2011-year closing article, to a summary of the nature of the bar, ^_^ ... Recently has been to the new students to do front-end training, but also to participate in the company's front-end recruitment, so the database inside a lot of efficient and useful knowledge to do some structured classification, and then share a summary of the front-end optimization. And the Spring Festival is also the peak of recruitment, in school, job-hopping, impetuous are beginning to enter the interview of the Army, front-end optimization is also a front-end interview will usually ask things, so hope to be useful to friends.

Front-End performance optimization

1. Please reduce HTTP requests

Basic:

When the browser (client) and server communication, it has consumed a lot of time, especially when the network situation is worse, this problem is particularly prominent.

The process of a normal HTTP request: If you type "www.xxxxxx.com" in the browser and press ENTER, the browser then establishes a connection to the server that the URL points to, and then the browser can send the request information to the server, and the server returns the corresponding information after receiving the requested information. After the browser receives an answer from the server, interpret the data for execution.

And when we request the Web page file has a lot of pictures, CSS, JS even music and other information, will be frequent connection with the server, and release the connection, which will cause a waste of resources, and each HTTP request to the server and browser performance burden.

With the same speed, download a 100KB picture faster than downloading two 50KB pictures. So, please reduce the HTTP request.

Solution:

Merge pictures (CSS sprites), merge CSS and JS files, more pictures of the page can also use lazyload technology to optimize.

2. Please understand Repaint and reflow correctly

Note: Repaint and reflow are redrawing and rearrangement, please allow me to show off the few English words I know. 囧

Basic:

Repaint (redrawing) occurs when an element's appearance is changed, but the layout (width and height) is changed, such as changing visibility, outline, background color, and so on.

Reflow (rearrangement) is the change in the DOM that affects the geometry of the element (width and height), the browser recalculates the element's geometric properties, invalidates the affected part of the render tree, and the browser verifies the visibility properties of all other nodes on the DOM tree. That's why reflow is inefficient. Such as: Change the size of the window, change the text size, content changes, browser window changes, style property changes and so on. If the reflow is too frequent, the CPU usage will miso to rise, so the front-end also need to know Repaint and reflow knowledge.

Ways to reduce performance impact:

The above mentioned that by setting the Style property to change the node style, each setting will cause a reflow, so it is best to set the way class; An animated element whose position property should be set to fixed or differs so that it does not affect the layout of other elements, and the smoothness of the speed is weighed if the functional requirements cannot be set position to fixed or differs.

In short, since reflow is sometimes unavoidable, it is only possible to limit the extent of Reflow's impact.

3. Please reduce the operation of the DOM

Basic:

The cost of DOM operations is high, which is usually a performance bottleneck in Web applications.

Born slowly. In the high performance JavaScript metaphor: "Think of the DOM as an island, the JavaScript (ECMAScript) as another island, a toll bridge." So each visit to the DOM will teach a bridge fee, and the more visits, the more money will be paid. So it is generally recommended to minimize the number of bridges.

Solution:

modifying and accessing DOM elements can result in repaint and reflow of the page, and looping over DOM operations is a more sinful behavior. So use JavaScript variables reasonably to store content, consider the performance overhead of a large number of DOM elements, and write at the end of the loop.

Reduces query and modification of DOM elements that can be assigned to local variables when queried.

Note: In IE: hover can reduce response speed.

4. Use JSON format for data exchange

Basic:

JSON is a lightweight data interchange format that uses a completely language-independent text format and is an ideal data interchange format. Also, JSON is the native format of JavaScript, which means that processing JSON data in JavaScript does not require any special APIs or toolkits.

As compared to XML serialization, JSON serialization produces data that is typically smaller than the volume of data after XML serialization, so a well-known web site such as Facebook uses JSON as a way of exchanging data.

JS Operation JSON:

In JSON, there are two kinds of structures: objects and arrays.

1. An object ends with "{" Beginning, "}". Each "name" followed by a ":"; Name/value pairs are delimited with the, (comma). The name is enclosed in quotation marks; If the value is a string, it must be enclosed in quotes, and the numeric type is not required. As:

var obj={"name": "Darren", "Age": "Location": "Beijing"}

2. An array is an ordered set of values (value). An array ends with "[" Beginning, "]". Values are separated by the "," (comma) value. As:

var jsonlist=[{"name": "Darren", "Age": "Location": "Beijing"},{"name": "Weidong.nie", "Age": "Location": "Hunan" }];

The manipulation of this array and object literals is very convenient and efficient. If you knew the JSON structure in advance, it would be wonderful to use JSON for data delivery, and you could write code that was practical and visually readable. If you're a purely front-desk developer, you'll love json very much.

5. Efficient use of HTML tags and CSS styles

Basic:

HTML is a language used to describe a Web page, which uses tag tags to describe a Web page, and as a qualified front-end developer, you need to know the meaning (SEO) and attributes (representation) of its commonly used tag representations.

CSS refers to cascading style sheet (cascading style Sheets), if you think of the page as a person, HTML is the skeleton of people, CSS is the clothing of people, a person's taste from his clothes can be at a glance.

A professional front-end development is also a good refactoring, because in the page often have a variety of unreasonable nested and repeatedly defined CSS styles, I do not want you to refactor the page, but I hope you encounter this situation to solve these problems. such as HTML:

<table><tr><td>
<table><tr><td>
...
</td></tr></table>
</td></tr></table>

or this CSS:

Body. box. Border ul Li P fervent span{color: #000}

These are very bad ways to use HTML and CSS.

Correct understanding:

HTML is a markup language, and you must understand its properties before using a reasonable HTML tag, such as Flow elements,metadata Elements, phrasing Elements. The basis of comparison is to know block-level elements and inline elements, box models, SEO knowledge.

CSS is used to render the page, but also the problem of rendering efficiency. CSS selectors are matched from right to left, where CSS selectors are sorted in order from small to large:

ID selector #box class selector. Box tag div pseudo class and pseudo element a:hover

When a page is triggered to cause reflux (reflow), inefficient selectors can still incur higher overhead, so avoid inefficiencies. #p # subtitle #e#

6. Using CDN Acceleration (content distribution Network)

Basic:

The full name of CDN is content IBuySpy receptacle, that is, contents distribution network.

"Its basic idea is to avoid as far as possible the internet is likely to affect the speed and stability of data transmission bottlenecks and links, so that content transmission faster and more stable." By placing node servers across the network, a layer of intelligent virtual networks based on the existing Internet, the CDN system can redirect the user's request to the nearest service node according to the network traffic and the connection of each node, the load status and the user's distance and response time. "-Baidu Encyclopedia.

Above a few words how many can settle read, so I still tell the story to introduce again, by the way, the story source is unknown, ^_^:

Ancient war we must all know, because the ancient traffic is very underdeveloped, so when the foreign attack often can not timely counterattack, such as the court levy soldiers again sent to the border when those invaders are already missing traces, this let ancient emperors are very depressed. Later emperors learned to be clever, all the troops sent to the border in advance, so that they usually land, wartime soldiers, such a strategy played a significant role.

Deficiencies:

The real time is not very good is a CDN's fatal flaw. As the demand for CDN grows, this flaw will be improved to keep the Web content pages from the remote server synchronized with the Web pages in the replica server or cache. The solution is to transfer new network content directly from the server side to the cache when the content of the network changes, or to replicate the data source server's network content to the cache server as quickly as possible when access to the network content increases.

7. CSS and JS to the external file reference, CSS put the head, JS put tail

Basic:

Note: This is a very basic and must follow the knowledge point, but for the integrity of the article to add in it, hehe.

The benefits of introducing an external file are obvious, and it is necessary to do so when the project is slightly more complex.

Easy to maintain, easy to expand, easy to manage and reuse.

Right way:

JavaScript is the dominant in the browser, why, because when the browser is executing JavaScript code, can not do other things at the same time, that <script> every time it will let the page wait for the script parsing and execution ( Whether JavaScript is embedded or out of the chain, the JavaScript code is finished before the page continues to render. This is also the blocking feature of JavaScript.

Because of this blocking feature, it is recommended that JavaScript code be placed before the </body> tag, so that it can effectively prevent JavaScript blocking, but also allows the HTML structure of the page to release faster.

The HTML specification clearly points out that CSS should be included in the <head> area of the page, and there is no more explanation.

8. Streamline CSS and JS files

Basic:

There is a very important rule that has not been mentioned, is CSS and JavaScript compression, directly reduce the volume of downloaded files. I often use the way is YUI compressor, it is characterized by: remove the annotation, remove the extra space, subtle optimization, identifier replacement.

YUI Compressor is a Java program, if you are familiar with the Java Word can quickly use Yuicompressor.jar; If you are unfamiliar to Java also does not matter, the same can be used Yui compressor, the following describes its use.

YUI compressor Configuration and use:

To configure the use environment first:

1. Ensure that the JDK is installed on the computer first

2. Configure the necessary environment variables (details can not be 32 sentences, so do not know how to set or search it)

3. In the CMD interface, enter Javac to test whether the installation is successful

Using the method can be from CMD to enter the Yuicompressor.jar disk, I take my own yuicompressor-2.4.2.jar as an example:

1. Compression JS

Java-jar Yuicompressor-2.4.2.jar api.js > Api.min.js

2. Compress CSS

Java-jar Yuicompressor-2.4.2.jar style.css > Style.min.css

  

Of course, there is another way to use more fool, to rush the interests of friends can go to try more.

9. Compress picture and use picture Spirit technology

Basic:

Note: In fact, compressed pictures and Picture Wizard is two aspects of technology, but since all is about the optimization of the picture or put it together.

Now because of the breakdown of the work, professional front-end engineers have few opportunities to cut the map, but the picture compression or a little understanding, the general image compression methods are:

1. Reduce the resolution of the picture;

2. Change the format of the picture;

3. Reduce the quality of picture preservation.

About the Picture Wizard (Spirit) technology is directly related to our work, whether in the CSS in the picture or in the HTML structure of the picture will produce an HTTP request, the front-end optimization of the first is to reduce the number of requests, the most direct and effective way is to use the Picture Wizard (CSS Spirit). Picture Wizard is to put a lot of pictures in a large picture inside, through the CSS to show a part of the picture.

As for the operation details of the picture elves do not introduce more, online related content a lot.

10. Note Control cookie size and pollution

Basic principles and methods of use:

The basics and advanced knowledge of cookies can be seen in an article I wrote "JavaScript manipulation cookies."

Because cookies are local disk files, each browser will read the corresponding cookies, so it is recommended to remove unnecessary coockie, so that the Coockie volume as small as possible to reduce the impact on user response;

When using cookies to cross domain operations, be aware of setting Coockie on the domain name of the adaptive level so that the subdomains are unaffected

Cookies are life-cycle, so be aware that setting reasonable expiration times, reasonably expire time, and not removing Coockie prematurely can improve user response time.

Time is limited, this year first come here, haha. Wish everyone a happy new year and smooth work. I will gradually improve this article in the future work, but also please mention valuable suggestions.

If we also have any good optimization method also please leave a message, will be added to this article, first of all thank you.

Resources

Baidu Encyclopedia

Http://dev.w3.org/html5/markup/common-models.html

http://www.w3schools.com/

Front Siege Master Raiders series

As a front-end siege division, more and more feel in the company's attention, there are more and more friends to join the front-end development of this post, there is a sense of pride.

Because I like reading books in my spare time, so had budding hope that the idea of writing a book, although now there are many pits need to step on, really want to write a book is also a long time later, but there is going to try to write points and the front end closely related to the strategy, so there is a "front introduction series."

Because of my ability to express and the lack of technical skills, it is inevitable to understand the wrong place, but also please a lot of understanding.

If you think this article is also the intention, please kindly click on the lower right corner of the recommended ^.^.

Author: Nievidong

Source: http://www.cnblogs.com/Darren_code/

This article copyright to the author and blog Park, Welcome to reprint, but without the consent of the author must retain this paragraph, and in the article page obvious location to the original connection.

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.