Summary of front end performance optimization

Source: Internet
Author: User

My front-end learning process

It is hard to imagine a half year ago still doing backstage development, to the front end know very little of me, now also can engage in front-end development. This half-year learning process will be my life a valuable treasure, which makes me think of a word "on the Road of growth, we do not set boundaries for themselves, as long as the strength of growth, can continue to surpass themselves ." In my own experience, I will talk about the learning process at the front end.

Read Catalogue

    • jquery Basic Knowledge preparation
    • CSS Learning and Skills
    • Code optimization
    • Summarize
Back to top jquery Basics Prep

Learning front-end needs to master the basic knowledge has jquery,css. Doing mobile-side development the best way to Master CSS3,CSS3 's many new features is to make the layout much simpler. jquery does not have to be skilled at every point of knowledge, but it is better to know that it is more secure to use it when it comes to careful learning. Several points that must be mastered

1. Selector

The base ID style selector is a must-have, not much to say here.

Non-recommended wording

<id= "foo"  onclick= "dosomething ()">Bar</  button>

Disadvantage: The result of this is the HTML front-end and JS front-end work mixed together, in principle, HTML code can only reflect the structure of the Web page

Suggested wording

$ ("#foo"). Click (function() {});

Advantages: jquery is an append binding, how much the tie is executed, and also resolves the incompatibility problem with IE.

There are many click,live,bind,one,on in the way of event binding in jquery ..., the difference between them here is not much to say. The on method is an officially recommended way to bind events, and is good for both performance and trial scenarios.

$ ("#foo"). On ("click",function() {});

Advanced usage, scenarios (a row is added dynamically in a multi-row table table, if you want to tie a fixed-point event to the new row)

$ ("#table"). On ("click", ". Row",function() {});

Here, when the page is initialized, you can bind the click event with row-style rows in the table, and even if row is new, the Click event, the event delegate, is added. In C #, the Publisher will publish the Click event to all Subscribers that inherit the row class, known as the publish-subscriber pattern.

3. function closure

It is recommended to encapsulate functions using closures to avoid function overrides.

var publichandle= (function () {/    * private variable and function */   var _privatevar;   var _getname=function() {            };   /* Externally available interfaces */   return {       VerifyName:function() {   },    getName:function() {    }}});

Grasp the several basic knowledge of jquery, combined with the front-end open task to JS will become more and more skilled.

Back to top CSS learning and tips

The main focus of CSS learning is to look more, you can learn others ready-made examples. See how the layout, CSS how to write is normative, online has a lot of ready-made resources such as W3cschool front-end network. Mobile development frameworks such as Agile Ratchet Junior.

The framework provides a lot of features that can be used directly, to understand one of the frameworks and CSS and JS will make their front-end learning more quickly, of course, it takes time.

Back to top of code optimization

Master the basics, you have to go to higher-level code and performance optimization, there are many front-end optimization guidance, the following comments cited the blog millisecond must contend, front page performance best practices. Best practices I quote from the Yahoo Front end Performance Team to summarize the 35 golden laws. The original is punched here. Here are some of the principles I understand.

Web content

    • Reduce the number of HTTP requests
    • Avoid page jumps
    • Reduce the number of DOM elements
    • Avoid 404

Server

    • Gzip Compressed transfer files
    • Avoid empty pictures of SRC

Cookies

    • Reduce cookie Size

Css

    • Pin a style sheet
    • Avoid CSS expressions

Javascript

    • Place the script on the bottom
    • Using external javascirpt and CSS files
    • Streamline JavaScript and CSS
    • Remove Duplicate Script
    • Reduce DOM Access

Web content reduces the number of HTTP requests

80% response time is spent on downloading Web content (images, stylesheets, javascripts, scripts, flash, etc.). reduce the number of requests is the key to shorten the response time! You can reduce the number of requests by simplifying the page design, but you can use the following tips for more page content.

1. Merging files : There are now many tools available to help you combine multiple script file files into one file, combining multiple stylesheet files into a single file to reduce the number of file downloads.

2.CSS Sprites: is to put a number of pictures into a picture, and then through the CSS to control where to show exactly where the whole picture. Let's see a familiar example of sprites.

The watercress put his icon together, and then we looked at how he controls display only the first picture of the cursor

 .app-icon-read  { Background-position :  0 0 ;} .app-icon  { background :  URL ("/pics/app/app_icons_ 50_5.jpg ") no-repeat scroll 0 0 transparent ;  Border-radius :  10px 10px 10px 10px  ;  Box-shadow :  1px 1px 2px #999999 ; Span style= "Color:rgb (255,0,0)" > display :  Inline-block ; :  50px ; :  50px ;} 

3.BASE64 encoding icon: Inserts a picture into the text of the Web page with an encoded string. For example, the following inline image is displayed as a checked checkbox.

{    padding-left: 20px;     background: white url (' data:image/png;  base64,ivborw0kggoaaaansuheugaaabaaaaaqaqmaaaalpw0iaaaablbmveuaaad///+l2z/daaaam0leqvr4ngp4/5/h/1+g/58zdraz3d/ MCH8YW83NDDENGE4UG9C9ZWZ3GVLMDA/A6P9/AFGGFYJOXZTQAAAAAELFTKSUQMCC ') No-repeat scroll left top;}

You can see that there is a long string, that is Base64 encoded image, online has generated tools. Picture Online conversion Base64

Reduce the number of DOM elements

Too many elements in the Web page load the Web page and the execution of the script is a heavy burden, the 500 elements and 5,000 elements in the loading speed will be very different. To find out how many elements are in your Web page, you can work out a simple command in the browser,

document.getElementsByTagName (' * '). length
Avoid 404

404 We are not unfamiliar, on behalf of the server did not find resources, we have to pay special attention to 404 of the situation do not on the Web resources we provide, the client sends a request but the server returned a useless result, time wasted. What's worse is that we need to load an external script in our web page and return a 404, which not only blocks other scripts from downloading, but also downloads the content (404) that the client will interpret as JavaScript.

Server gzip Compressed transfer files

Gzip can typically reduce the size of 70% of Web pages, including scripts, stylesheets, pictures, and more. Gzip is more efficient than deflate, and mainstream servers have corresponding compression support modules. IIS has built-in static compression and dynamic compression modules, how to formulate can refer to enable HTTP Compression of static content (IIS 7) and enable HTTP Compression of the dynamic content (I is 7).

It is important to note that the PDF file can be removed from the type that needs to be compressed, because the PDF file itself is compressed, gzip is less effective, and it wastes CPU.

Avoid empty pictures of SRC

The empty image src still causes the browser to send requests to the server, which is a waste of time and wastes the resources of the server. Especially if your website is visited by many people every day, the damage caused by such an empty request cannot be ignored. The browser implementation is also based on the RFC 3986–uniform Resource identifiers Standard, empty SRC is defined as the current page. So notice if there's such a code in our web page.

Straight HTML<src= "">javascriptvar img = new Image (); img.src = "";
Cookie reduction Cookie Size

Cookies are used for authentication or personalization, their information is included in the HTTP header, and for cookies we should pay attention to the following points to improve the response speed of the request,

    • Remove unnecessary cookies, which are completely banned if the Web page does not require a cookie
    • Minimize the size of cookies
    • Note that the cookie is set to the domain level and does not affect the sub-domain if necessary
    • Set the appropriate expiration time, and the longer expiration time can increase the response speed.
CSS pinned style sheets

Putting a style sheet (CSS) in the head of a webpage makes the page load faster, because doing so allows the browser to incrementally load the content of the Web page that has been downloaded. This is especially important for pages that are more content, and users don't have to wait on a white screen to see what they have already downloaded.

If you put the style sheet at the bottom, the browser refuses to render the page that has already been downloaded, because most browsers try to avoid redrawing when they are implemented, and the content in the stylesheet is the key information for drawing the page, so I'm sorry for the audience without downloading it.

Avoid CSS expressions

CSS expressions can be dynamically set CSS properties, supported in IE5-IE8 , and expressions in other browsers will be ignored . For example, the following expression sets different background colors at different times.

Background-color:expression (New Date ()). GetHours ()%2  "#B8D4FF": "#F08A00");

The problem with CSS expressions is that it is recalculated more often than we think, not only when the page is drawn or resized, but even when we are scrolling the screen or moving the mouse, so we try to avoid using it to prevent improper use of performance loss. We can do this with a simple script if we want to achieve a similar effect.

<HTML><Head></Head><Body><Scripttype= "Text/javascript">varCurrentTime =NewDate (). GetHours ();if(currenttime%2) {if(document.body) {document.body.style.background = "#B8D4FF"; }}Else{if(document.body) {document.body.style.background = "#F08A00"; }}</Script></Body></HTML>
JavaScript to place the script bottom

http/1.1 specification recommends that browsers do not have more than two concurrent download connections to the same hostname, so you can increase the number of concurrent download connections when you download pictures from multiple domain. However, when the script is downloaded, the other resources are not downloaded even from different hostname browsers because the browser is parsed and executed sequentially after the script is downloaded.

So for the script to speed up, we can consider the following ways,

    • Put the script down so that the content needed to render the page is loaded as soon as it appears to the user.
    • The DEFER keyword is now supported in mainstream browsers, and you can specify that the script executes after the document is loaded.

The Async keyword is added to the HTML5 to allow the script to execute asynchronously.

Using external javascirpt and CSS files

Using external JavaScript and CSS files allows these files to be cached by the browser and reused between different request content. Turning JavaScript and CSS from inline to external also reduces the size of Web content. The decision to use external JavaScript and CSS files depends on the reuse rate of these external files, and the external file form can be a great benefit if the user browses to our page and accesses multiple pages of the same page or can reuse the script. But for a page that the user usually accesses only once, such as the Microsoft.com homepage, the inline JavaScript and CSS provide a relatively high level of efficiency.

Streamline JavaScript and CSS

Simplification is to remove the space and comments in JavaScript or CSS, to help us do a lot of thin tools, mainly can refer to the following,

JS Compressors:

    • Packer
    • Jsmin
    • Closure compiler
    • Yuicompressor (also does CSS)
    • Ajaxmin (also does CSS)

CSS Compressors:

    • Csstidy
    • Minify
    • Yuicompressor (also does JS)
    • Ajaxmin (also does JS)
    • Csscompressor

The tools that are better with VS integration are as follows.

    • yuicompressor-compilation integration, included in NuGet.
    • ajaxmin– Compilation Integration
Remove Duplicate Script

Duplicate scripts not only waste the browser's download time, but also waste parsing and execution time. It is generally used to avoid introducing duplicate scripts by using a unified script management module, which not only avoids repetitive script introductions, but also allows for scripting dependency management and versioning.

Reduce DOM Access

Accessing DOM elements via JavaScript is not as fast as we think, the pages with many elements are especially slow, and for JavaScript access to the DOM we should note

    • Cache elements that have already been accessed
    • Offline Update node and add back Dom Tree
    • Avoid repairing layout with JavaScript

Back to top of the summary

After this time of the front-end learning, deep understanding of the front end is actually similar to the back end. Learning process can be an analogy, the beginning of learning is to complete the function, when the code is skilled to know the content of the code optimization, understand what code is good code, why so write is good code. Such a process of learning can make oneself progress faster, not just to realize the function.

Another point is to share, only they will learn the knowledge of the firm, only the ability to share knowledge, which is to help their own ascension process.

Perhaps you will feel that I do not need to grasp the front end of the backend, but perhaps when you need to engage in front-end it! Do well in advance knowledge Reserve, keep a tireless knowledge of the heart, status quo is not better, you say?

Summary of front end performance optimization

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.