Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the basic performance optimization rules of web pages

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

Editor to share with you what are the basic performance optimization rules of the web page, I believe most people do not know much about it, so share this article for your reference, I hope you will learn a lot after reading this article. Let's learn about it!

Some optimization rules for browser web pages

Page optimization

Static resource compression

With the help of building tools (webpack, gulp) to properly compress the static resources of web pages such as pictures, scripts and styles.

CSS Sprite, base64 inline pictures

Merge the small icons inside the site into one picture, and use css to locate and intercept the corresponding icons; use inline images as appropriate.

Style at the top and script at the bottom

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

Use css and js outside the chain

Multiple pages refer to public static resources, and resource reuse reduces additional http requests.

Avoid empty src images

Avoid unnecessary http requests.

image

Avoid zooming pictures in html

Try to use the specified size as needed, instead of loading a large picture and shrinking it.

image

Preload preloading

Setting the preload attribute on the rel of the link tag allows the browser to preload the asset before the main rendering mechanism intervenes. This mechanism can obtain resources earlier without blocking the initialization of the page.

Document

In the example, the css and js files are preloaded and will be called as soon as they are used in subsequent page rendering.

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

Style

Script

Video

Audio

Image

Font

Document

...

This method can also preload resources across domains and set the crossorigin attribute.

CSS

Selector

The priority of the selector is arranged from high to low:

ID selector

Class selector

Tag selector

Adjacent selector

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

Select the paragraph that appears immediately after the H2 element, where H2 and p elements have a common parent element.

Subselector

H2 > strong {color:red;}

Descendant selector

H2 em {color:red;}

Wildcard selector

Attribute selector

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

Pseudo class selector

Experience in using selector:

Preferred class selector to replace multi-layer tag selector

Use the ID selector with caution. Although it is efficient, it is unique on the page and is not conducive to team collaboration and maintenance.

Make rational use of the inheritance of selectors

Avoid css expressions.

Reduce the level of selector

Based on the priority of the previous selector, try to avoid multi-level selector nesting, preferably no more than 3 layers.

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

Simplify page style files and get rid of unused styles

The browser will make extra style matching, which will affect the rendering time, and the large style file will also affect the loading speed.

Reduce the amount of code by using css inheritance

With the inheritable attributes of css, the parent element is styled and the child element is no longer set.

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

When the attribute value is 0, no units are added.

When the value of the css attribute is 0, the amount of code can be reduced without adding units.

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

JavaScript

Use event delegation

Use event delegates for binding events to multiple DOM elements of the same kind.

1 / 23 click / unreasonable way: bind each element to the click event $('# container. List'). On ('click', function () {var text = $(this). Text (); console.log (text);}) / / event delegation: use the event bubbling mechanism to delegate the event to the parent element $('# container') .on ('click',' .list', function () {var text = $(this) .text (); console.log (text);})

It should be noted that although events can be delegated to document when using event delegates, this is unreasonable. One is easy to cause misjudgment of events, and the other is that the search efficiency of scope chain is low. You should select the nearest parent element as the delegate object.

In addition to better performance using event delegates, dynamically created DOM elements no longer need to bind events.

DOMContentLoaded

You can start processing the DOM tree after the DOM element has been loaded (DOMContentLoaded), and you don't have to wait until all the image resources have been downloaded.

/ Native javascriptdocument.addEventListener ("DOMContentLoaded", function (event) {console.log ("DOM fully loaded and parsed");}, false); / / jquery$ (document) .ready (function () {console.log ("ready!");}); / / $(document). Simplified version of ready () (function () {console.log ("ready!");})

Preloading and lazy loading

Preload

Use the browser's idle time to preload resources that may be used in the future, such as pictures, styles, and scripts.

Unconditional preloading

As soon as the onload is triggered, get the resources you need in the future.

Picture resources are preloaded. (3 ways to realize picture preloading).

Preloading based on user behavior

Judge the possible actions of the user behavior and preload the resources that may be needed in the future.

When the user enters in the search input box, preload the resources that may be used by the search results page

When a user manipulates a Tab tab, one of them is displayed by default. When you want to click (click) other options, you can load the resources that will be used in the future when you hover the mouse.

Lazy loading

You can delay loading except for the content or components needed for page initialization, such as js libraries that cut images, images that are not in visual range, and so on.

Pictures are loaded lazily. (determine whether the picture is within the visual area, and if so, assign the real path to the picture)

Avoid global lookup

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 iTun0, len=imgs.length; I < len; iTunes +) {imgs.title = document.title + "image" + I;} var msg = document.getElementById ("msg"); msg [XSS _ clean] = "Update complete.";}

The document global variable is used many times in the above function, especially in the for loop. Therefore, it is better to store document global variables as local variables and then use them.

Function updateUI () {var doc = document; var imgs = doc.getElementsByTagName ("img"); for (var iTun0, len=imgs.length; I < len; iCool +) {imgs.title = doc.title + "image" + I;} var msg = doc.getElementById ("msg"); msg [XSS _ clean] = "Update complete.";}

It is worth noting 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 attribute queries

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

/ use array var values = [5,10]; var sum = values [0] + values [1]; alert (sum); / / use 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 property lookup once or twice will not cause performance problems, but if multiple lookups are needed, such as in a loop, it will affect performance.

When getting multiple attribute lookups for a single value, such as:

Var query = _ window.location.href.substring_ (window.location.href.indexOf ("?")

Unnecessary attribute lookups should be reduced and _ window.location.href should be cached as variables.

Var url = _ window.location.href;var query = url.substring (url.indexOf ("?")

Function throttling

Suppose you have a search box that binds an onkeyup event to the search box so that a request is sent every time the mouse is raised. By using the throttling function, the continuous operation of the user within a specified period of time can be guaranteed to trigger only one request.

/ / bind event document.getElementById ('input'). AddEventListener (' keyup', function () {throttle (search);}, false); / / logical function function search () {console.log ('search...');} / / Throttle function 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 the search box, such as scrolling onscroll of the page, onresize of stretch window, etc., should use throttle function to improve performance.

Minimize the number of statements

The number of statements is also a factor that affects the speed of operation execution.

Merge multiple variable declarations into a single variable declaration

/ / use multiple var statements var count = 5bossvar color = "blue"; var values = [1meme 2blue 3]; var now = new Date (); / / improved var count = 5, color = "blue", values = [1mem2jue 3], now = new Date ()

The improved version uses only one var declaration, separated by commas. When there are many variables, it is much faster to use a single var declaration than to declare a single var separately.

Use arrays and object literals

Use arrays and objects literally instead of assigning values one statement at a time.

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

String optimization

String concatenation

Early browsers did not optimize the concatenation of strings with plus signs. Because strings are immutable, it means that intermediate strings are used to store results, so frequent creation and destruction of strings is the reason for its inefficiency.

Var text = "Hello"; text+= ""; text+= "World!"

By adding a string to an array and then calling the array's join method to convert it to a string, you avoid using the addition operator.

Var arr = [], I = 0poliarr [ionization +] = "Hello"; arr [iTunes +] = ""; arr [iTunes +] = "World!"; var text = arr.join ('')

Today's browsers optimize string plus sign concatenation, so in most cases, the addition operator is the first choice.

Reduce backflow and redraw

During browser rendering, backflow and redrawing are involved, which is a process that consumes performance, and attention should be paid to reducing the actions that trigger reflow and redrawing during script operations.

Reflow: the geometric properties of the element have changed and the render tree needs to be rebuilt. The process in which the render tree changes is called reflux.

Redraw: the geometric size of an element has not changed, but the CSS style (background color or color) of an element has changed.

What are the actions that trigger rearrangement or redrawing?

Resize the window

Modify font

Add or remove style sheets

Content changes, such as when the user enters text in the box

Manipulate the class property

Script operation DOM (add, delete, or modify DOM elements)

Calculate offsetWidth and offsetHeight properties

Set the value of the style property

How to reduce rearrangement and redraw and improve web performance?

1. Script operation DOM element

Setting the DOM element to display:none will trigger a reflow during the setting process, but you can change it at will, and then display it after modification.

Clone the element into memory before operating, and replace the element again after modification.

2. Modify the style of the element

Try to modify it in batches instead of one by one

Set id and class in advance, and then set the className of the element.

3. When adding animation to the element, set the element CSS style to position:fixed or position:absolute, and the element will not cause backflow after it is separated from the document stream.

4. Use throttling function (mentioned above) when adjusting window size, input box input, page scrolling and other scenarios.

HTTP

Browser cach

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

Expires and Cache-Control

Expires comes from HTTP1.0,Cache-Control and comes from HTTP1.1. If you set both, Cache-Control will overwrite Expires.

Expires specifies the actual expiration date rather than the number of seconds. However, Expires has some problems, such as the server time is out of sync or inaccurate. Therefore, it is best to use the number of seconds left rather than absolute time to express the expiration time.

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 ETag and Last-Modified are returned in response headers by the server, where ETag has a higher priority than Last-Modified, which means that the server will give priority to the value of ETag.

An ETag is any tag attached to a document, which may be the serial number or version number of the document, or a check of the content of the document, etc. The ETAG value changes when the document changes. Related to ETag is If-None-Match. When a browser initiates a request, it sends the value of ETag to the server in the If-None-Match field.

Last-Modified is the time when the document was last modified on the server side. Related to Last-Modified is If-Modified-Since, which is sent to the server with the value of Last-Modified in the If-Modified-Since field when the browser initiates a request.

Strong caching and negotiation caching

The type of cache is strong cache and negotiation cache. The difference between the two is that strong cache will not send a request to the server, while negotiation cache will send a request. 304 Not Modified will be returned if the match is successful, and 200 will be returned if the match is unsuccessful. The browser will verify the strong cache first, and then check the negotiation cache if the strong cache fails.

How to configure browser caching

Add Expires and Cache-Control to the response of the web server

Configure Expires and Cache-Control in the configuration file of nginx or apache.

Why reduce HTTP requests

Measures to reduce http requests account for a large part of performance optimization, such as using css sprite images instead of multiple images, avoiding empty src images, using inline images, using outer-linked css and js, caching, and so on.

The process from entering URL to page loading includes:

DNS parsing

TCP connection

HTTP request and response

Browser render page

Close the connection

A complete http request goes through these processes, which is time-consuming and resource-consuming, so it is necessary to reduce the number of requests.

The above is all the contents of the article "what are the basic performance optimization rules of web pages". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report