Basic performance optimization for front-end Web pages

Source: Internet
Author: User
Tags browser cache
This time for everyone to bring the front page basic performance optimization, the attention to what matters, the following is the actual case, take a look.

Page optimization

Static resource compression

Use the Build tool (Webpack, gulp) to properly compress Web page static resources such as pictures, scripts, and styles.

CSS sprite diagram, base64 inline picture

The small icon in the station is merged into a picture, using the CSS to locate the corresponding icon, use the inline picture appropriately.

Style pinned, script bottom

The page is a gradual rendering process, the style top can render the page more quickly to the user;<script> tag pinned will block the download of resources behind the page.

Using CSS and JS outside the chain

Multiple pages reference a public static resource, and resource reuse reduces additional HTTP requests.

Picture of avoiding empty src

Avoid unnecessary HTTP requests.

<!--empty SRC image will still initiate HTTP request-->

Avoid scaling pictures in HTML

The picture tries to use the size of the specified specification as needed instead of loading a large picture and shrinking it.

<!--actual picture size is 600x300, scaled in HTML in order to 200x100-->

Preload Pre-load

Setting the Preload property to the rel of the link label allows the browser to preload resources before the main rendering mechanism intervenes. This mechanism can obtain resources earlier and does not block the initialization of the page.

<! DOCTYPE html>

In the example, the CSS and JS files are preloaded, and in the subsequent page rendering, they are immediately invoked once they are used.

You can specify the type of as to load different types of resources.

    1. Style

    2. Script

    3. Video

    4. Audio

    5. Image

    6. Font

    7. Document

    8. ...

This way you can also preload resources across domains, setting the Crossorigin property.

<link rel= "preload" href= "fonts/cicle_fina-webfont.woff2" as= "Font" type= "font/woff2" crossorigin= "Anonymous" >

Css

Selector Selector

The priority of the selector is arranged from highest to lowest:

    1. ID Selector

    2. Class Selector

    3. Tag Selector

    4. Adjacent selector

H1 + p{margin-top:15px;}

Select the paragraph that appears immediately after the H1 element, and the H1 and P elements have a common parent element.

Child Selector

H1 > Strong {color:red;}

Descendant Selector

H1 em {color:red;}

Wildcard Selector

Property Selector

*[title] {color:red;} Img[alt] {border:5px solid red;}

Pseudo class Selector

Experience with selectors:

    1. Preferred class selector, alternative to multi-layer tag Selector;

    2. Careful use of ID selector, although it is efficient, but in the page is unique, not conducive to team collaboration and maintenance;

    3. Reasonable use of the successor of the selector;

    4. Avoid CSS expressions.

Reduce the hierarchy of selectors

Based on the priority of the previous selector, you should try to avoid nesting multiple levels of selectors, preferably not more than 3 layers.

. container. Text. logo{color:red;} /* Change to */.container. text-logo{color:red;}

Streamline page style files and remove unused styles

The browser will do the extra style matching, affect the rendering time, in addition, the style file too large will affect the loading speed.

Reduce the amount of code with CSS inheritance

With the inheritable properties of the CSS, the parent element sets the style, and the child element is no longer set.

Common inheritable properties such as: color,font-size,font-family, etc., non-inheritable such as: position,display,float, etc.

Property value is 0 o'clock, no units

The CSS property has a value of 0 o'clock, which reduces the amount of code without adding units.

. text{width:0px; height:0px;} /* Change to */.text{width:0; height:0;}

Javascript

Using event delegates

Use event delegates to bind events to multiple homogeneous DOM elements.

<ul id= "Container" >  <li class= "list" >1</li>  <li class= "list" >2</li>  <li class= "List" >3</li></ul>
Unreasonable way: To bind each element to the Click event $ (' #container. List '). On (' click ', Function () {  var text = $ (this). text ();  Console.log (text);}); /Event Delegation: Use event bubbling to delegate events uniformly to the parent element $ (' #container '). On (' click ', '. List ', function () {  var text = $ (this). text ();  Console.log (text);    });

It is important to note that although event delegates can be used to delegate events to document, this is unreasonable, one is prone to event miscalculation, and the other is the inefficient scope chain lookup. The closest parent element should be selected as the delegate object.

Using event delegates in addition to better performance, dynamically created DOM elements do not require a rebinding event.

domcontentloaded

You can start processing the DOM tree after the DOM element has finished loading (domcontentloaded), without having to wait until all of the picture resources have been downloaded and processed.

Native Javascriptdocument.addeventlistener ("domcontentloaded", function (event) {  Console.log ("DOM Fully Loaded and Parsed ");}, false);//jquery$ (document). Ready (function () {  console.log (" ready! ");}); /$ (document). Ready () simplified version $ (function () {  console.log ("ready!");});

Pre-loading and lazy loading

Pre-load

Use browser idle time to preload resources, slices, styles, and scripts that might be used in the future.

Pre-loaded unconditionally

Once the onload is triggered, immediately get the resources you need to use in the future.

Pre-load the picture resource. (3 ways to implement picture preloading).

Pre-load based on user behavior

Determine what actions a user's behavior might make, and preload resources that might be needed in the future.

    1. The resources that may be used to pre-load the search results page when the user enters the search input box;

    2. When the user to operate a tab tab, the default display of one, when the click (click) Other options, when the mouse hover, you can first load the future use of resources;

Lazy Loading

In addition to the content or components required for page initialization, others can be delayed loading, such as the JS library for cutting pictures, images not in the viewable range, and so on.

Picture lazy loading. (Determines whether the picture is within the viewable area, and if so, assigns the true path to the picture)

Avoid global lookups

Any non-local variable that is used more than once in a function should be stored as a local variable.

function UpdateUI () {  var IMGs = document.getelementsbytagname ("img");  For (var i=0, len=imgs.length; i < Len; i++) {    imgs[i].title = document.title + "image" + i;  }  var msg = document.getElementById ("msg");  msg.innerhtml = "Update complete.";}

The document global variable is used more than once in the above function, especially in the For loop. Therefore, it is better to store the document global variable as a local variable.

function UpdateUI () {  var doc = document;  var IMGs = doc.getelementsbytagname ("img");  For (var i=0, len=imgs.length; i < Len; i++) {    imgs[i].title = doc.title + "image" + i;  }  var msg = Doc.getelementbyid ("msg");  msg.innerhtml = "Update complete.";}

It is important to note that in JavaScript code, any variable that is not declared with Var becomes a global variable, and improper use can cause performance problems.

Avoid unnecessary property queries

Using variables and arrays is more efficient than accessing properties on an object, because an object must search for properties that have that name in the prototype chain.

Use the array var values = [5, 10];var sum = values[0] + values[1];alert (sum);//Use the object var values = {first:5, Second:10};var sum = Values.first + values.second;alert (sum);

In the above code, the object properties are used to calculate. A two-time property lookup does not cause performance problems, but if multiple lookups are required, such as in a loop, performance is affected.

When you get a multiple-attribute lookup for a single value, such as:

var query = window.location.href.substring (Window.location.href.indexOf ("?"));

You should reduce unnecessary property lookups and cache window.location.href as variables.

var url = window.location.href;var query = url.substring (Url.indexof ("?"));

function throttling

Suppose you have a search box that binds the onkeyup event to the search box so that every time the mouse lifts, it sends a request. Using the throttle function, you can guarantee that the user will trigger only one request at a specified time during the input.

<input type= "text" id= "input" value= ""/>
Bind event document.getElementById (' input '). AddEventListener (' KeyUp ', function () {  throttle (search);}, false);// Logical functions function Search () {  console.log (' Search ... ');} Throttling functions function throttle (method, context) {  cleartimeout (method.tid);  Method.tid = SetTimeout (function () {    method.call (context);  }, 300);}

The application scenario of throttle function is not limited to search box, such as scrolling onscroll of page, drawing window onresize etc. should use throttle function to improve performance.

Minimum number of statements

The number of statements is also a factor that affects how fast the operation is performed.

Merging multiple variable declarations into one variable declaration

Use multiple var to declare var count = 5;var color = "Blue"; var values = [1,2,3];var now = new Date ();//Improved var count = 5,  color = "b Lue ",  values = [n/a], now  = new Date ();

The improved version is only using a var declaration, separated by commas. When variables are large, using only one VAR declaration is much faster than a single VAR declaration.

Using arrays and object literals

Use arrays and object literals in a way that replaces each statement assignment.

var values = new Array (); values[0] = 123;values[1] = 456;values[2] = 789;//improved var values = [123, 456, 789];
var person = new Object ();p erson.name = "Jack";p erson.age = 28;person.sayname = function () {  alert (this.name);};/ /improved var person = {  Name: "Jack",  age:28,  sayname:function () {    alert (this.name);  }};

String optimization

string concatenation

The previous browser did not optimize the plus-stitch string. Because the string is immutable, it means that the result is stored using an intermediate string, so the frequent creation and destruction of the string is the cause of its inefficiency.

var text = "Hello"; text+= ""; text+= "world!";

Adding a string to an array, and then invoking the join method of the array into a string, avoids the use of the addition operator.

var arr = [],  i = 0;arr[i++] = "Hello"; arr[i++] = ""; arr[i++] = "world!"; var text = Arr.join (");

Now browsers are optimized for string plus concatenation, so in most cases the addition operator is preferred.

Reduced reflow and redraw

In the browser rendering process, it involves reflow and repainting, which is a loss performance process, and you should be aware that the actions that trigger reflow and redraw are reduced during script operations.

    1. Reflow: The geometry properties of the element have changed, and the render tree needs to be rebuilt. The process of changing the rendering tree is called reflux;

    2. Redraw: The geometry size of the element has not changed, and the CSS style (background color or color) of an element has changed.

What are the actions that trigger a reflow or redraw?

    1. resizing windows

    2. Modify Font

    3. Add or remove style sheets

    4. Changes in content, such as users entering text in the <input/> box

    5. Operation Class Property

    6. Script manipulation Dom (adding, deleting, or modifying DOM elements)

    7. Calculate Offsetwidth and Offsetheight properties

    8. Set the value of the Style property

How can I reduce reflow and redraw to improve Web page performance?

1. Script Manipulation DOM elements

    1. The DOM element is set to Display:none, the setting process will trigger a reflow, but then can be arbitrarily changed, after modification and display;

    2. Clone the element into memory and then re-replace the element after the modification.

2. Modify the style of the element

    1. As far as possible in batch modification, not article by article;

    2. Pre-set the ID, class, and then set the classname of the element.

3. When animating an element, the element CSS style is set to position:fixed or Position:absolute, and the element does not cause reflux after it is detached from the document stream.

4. Use the throttle function (mentioned above) when resizing scenes such as window size, input box input, page scrolling, etc.

HTTP

Browser cache

Reasonable setting up browser cache is one of the important means of web optimization.

Expires and Cache-control

Expires from Http1.0,cache-control from HTTP1.1, and when both are set, Cache-control overrides Expires.

    1. expires specifies the actual expiration date instead of the number of seconds. However, there are some problems with expires, such as server time is out of sync or inaccurate. So it's best to use the remaining seconds instead of the absolute time to express the expiration time.

    2. Cache-control can set the Max-age value, in seconds, to specify the cache expiration time. such as: cache-control:max-age=3600.

ETag and Last-modified

Both the ETag and the last-modified are returned by the server in response headers, where the etag has a higher priority than last-modified, which means the server will prioritize the ETag value.

    1. An etag is any label attached to a document, which may be the serial number or version number of a document, or a checksum of the contents of a document. The ETag value also changes as the document changes. The etag is related to the If-none-match, when the browser initiates the request, will carry the value of the ETag in the If-none-match field to the server;

    2. Last-modified is the time at which the document was last modified on the server side. Related to Last-modified is if-modified-since, which, when the browser initiates a request, sends the value last-modified in the If-modified-since field to the server.

Strong caching and negotiation caching

The cached type strongly caches and negotiates the cache. The difference is that the strong cache will not send a request to the server, and the negotiation cache will send a request, the match is successfully returned 304 not Modified, the match does not return 200 successfully, the browser checks the strong cache first, if the strong cache misses, then the negotiation cache check.

How to configure browser caching

    1. Add expires and Cache-control to the return response of the Web server;

    2. Configure expires and Cache-control in the Nginx or Apache configuration file.

Why to reduce HTTP requests

The reduction of HTTP requests in performance optimization takes a large part, such as using CSS Sprite to replace requests for multiple images, avoiding empty src images, using inline images, using the outer chain of CSS and JS, caching, and so on.

The process from input URL to page load completion includes:

    1. DNS resolution

    2. TCP connections

    3. HTTP requests and Responses

    4. Browser Rendering page

    5. Close connection

Believe that you have read the case of this article you have mastered the method, more exciting please pay attention to the PHP Chinese network other related articles!

Recommended reading:

Code and order of writing in CSS real-combat project

Css+transition make explicit animations

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.