Some optimization rules for browser web pages
Page optimization Static resource compressionUse construction tools (webpack, gulp) to appropriately compress web page static resources such as images, scripts, and styles.
CSS sprite images, base64 inline imagesMerge the small icons on the site into one image, use CSS to position and intercept the corresponding icons; use inline images appropriately.
Styles at the top and scripts at the bottomThe page is a step-by-step rendering process. Sticking the style to the top can present the page to the user faster; sticking the <script> tag to the top will block the download of resources behind the page.
Use css and js of external linksMultiple pages reference public static resources, and resource reuse reduces additional http requests.
Avoid images with empty srcAvoid unnecessary http requests.
<!-- Images with empty src will still initiate http requests--><img src= style="margin: 0px; padding: 0px; outline: none; line-height: 25.2px; font-size: 14px; width: 660px; overflow: hidden; clear: both; font-family: tahoma, arial, Microsoft YaHei;"><!-- The actual image size is 600x300, which is scaled to 200x100 in html --><img src=/static/images/a.png width=200 height=100 style="margin: 0px; padding: 0px; outline: none; line-height: 25.2px; font-size: 14px; width: 660px; overflow: hidden; clear: both; font-family: tahoma, arial, Microsoft YaHei;"><!DOCTYPE html><html lang=en><head> <meta charset=UTF-8> <title>Document</title> <link ref=preload href=style.css as=style> <link ref=preload href =main.js as=script> <link ref=stylesheet href=style.css></head><body> <script src=main.js></script></body></html>In the example, css and js files are preloaded, and they will be called immediately once they are used in subsequent page renderings.
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 by setting the crossorigin attribute.
<link rel=preload href=fonts/cicle_fina-webfont.woff2 as=font type=font/woff2 crossorigin=anonymous>CSS selectorThe priority of the selectors from high to low is:
- ID selector
- class selector
- tag selector
- adjacent selector
h1 + p{ margin-top: 15px; }Selects the paragraph that appears immediately after the h1 element. The h1 and p elements have a common parent element.
child selector
h1 > strong {color:red;}descendant selector
h1 em {color:red;}wildcard selector
attribute selector
*[title] {color:red;}img[alt] {border: 5px solid red;}Pseudo class selector
Selector usage experience:
Reduce the level of selectors
- Prioritize class selectors, which can replace multi-layer label selectors;
- Use the ID selector with caution. Although it is efficient, it is unique in the page and is not conducive to team collaboration and maintenance;
- Make reasonable use of selector inheritance;
- Avoid css expressions.
Based on the priority of the previous selector, you should try to avoid multiple levels of selector nesting, preferably no more than 3 levels.
.container .text .logo{ color: red; }/*Change to*/.container .text-logo{ color: red; }Streamline page style files and remove unused stylesThe browser will perform redundant style matching, which will affect rendering time. In addition, excessively large style files will also affect loading speed.
Use css inheritance to reduce code sizeUsing the inheritable properties of CSS, the parent element sets the style, and the child elements do not need to set it again.
Common inheritable attributes include: color, font-size, font-family, etc.; non-inheritable attributes include: position, display, float, etc.
When the attribute value is 0, no unit is added.When the css attribute value is 0, no unit can be added to reduce the amount of code.
.text{ width: 0px; height: 0px; }/*Change to*/.text{ width: 0; height: 0; }JavaScriptUse event delegation
Use event delegation to bind events to multiple similar DOM elements.
<ul id=container> <li class=list>1</li> <li class=list>2</li> <li class=list>3</li></ul>// Unreasonable way: bind click event to each element $('#container .list').on('click', function() { var text = $(this).text(); console. log(text);});//Event delegation method: Use the event bubbling mechanism to delegate events to the parent element $('#container').on('click', '.list', function() { var text = $(this).text(); console.log(text); });It should be noted that although the event can be delegated to the document when using event delegation, this is unreasonable. One is that it easily causes event misjudgment, and the other is that the scope chain search efficiency is low. The closest parent element should be selected as the delegate.
In addition to better performance, using event delegation also eliminates the need to bind events to dynamically created DOM elements.
DOMContentLoadedYou can start processing the DOM tree after the DOM elements are loaded (DOMContentLoaded), instead of waiting until all image resources are downloaded.
// Native javascript document.addEventListener(DOMContentLoaded, function(event) { console.log(DOM fully loaded and parsed);}, false);// jquery$(document).ready(function() { console.log(ready! );});// Simplified version of $(document).ready()$(function() { console.log(ready!);});Preloading and lazy loading preloadUse the browser's idle time to preload resources that may be used in the future, such as images, styles, and scripts.
Unconditional preloadingOnce onload is triggered, resources that will be needed in the future are immediately obtained.
Image resources are preloaded. (3 ways to implement image preloading).
Preloading based on user behaviorJudge the possible operations of user behavior and pre-load resources that may be needed in the future.
Lazy loading
- When the user types in the search input box, resources that may be used on the search results page are preloaded;
- When the user operates a Tab, one of them will be displayed by default. When clicking on other options, the resources that will be used in the future can be loaded first when the mouse hovers;
Except for the content or components required for page initialization, everything else can be loaded lazily, such as js libraries that cut pictures, pictures that are not in the visible range, etc.
Images are lazy loaded. (Determine whether the picture is within the visible area, if so, assign the real path to the picture)
Avoid global lookupAny non-local variable 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 many times in the above function, especially in the for loop. Therefore, it is a better solution to store document global variables as local variables and then use them.
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.;}One thing worth noting is that in JavaScript code, any variable not declared using var will become a global variable, and improper use will cause performance problems.
Avoid unnecessary attribute queriesUsing variables and arrays is more efficient than accessing properties on an object because the object must search the prototype chain for a property with that name.
//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, object properties are used to calculate. Searching properties once or twice will not cause performance problems, but if multiple searches are required, such as in a loop, performance will be affected.
When looking up multiple attributes to get a single value, like:
var query = window.location.href.substring(window.location.href.indexOf(?));Unnecessary attribute lookups should be reduced and window.location.href should be cached as a variable.
var url = window.location.href;var query = url.substring(url.indexOf(?));function throttlingSuppose there is a search box, bind the onkeyup event to the search box, so that a request will be sent every time the mouse is raised. The use of throttling functions can ensure that multiple consecutive operations by the user within a specified time of input only trigger one request.
<input type=text id=input value= />// Bind event document.getElementById('input').addEventListener('keyup', function() { throttle(search);}, false);// Logic 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 scenarios of the throttling function are not limited to the search box. For example, onscroll of the page, onresize of the stretched window, etc., the throttling function should be used to improve performance.
Minimize the number of statementsThe number of statements is also a factor that affects the speed of operation execution.
Combine multiple variable declarations into one variable declaration
// Use multiple var declarations var count = 5; var color = blue; var values = [1,2,3]; var now = new Date(); // After improvement, var count = 5, color = blue, values = [1,2,3], now = new Date();An improved version is to use just one var declaration, separated by commas. When there are many variables, using only one var declaration is much faster than declaring individual vars separately.
Using arrays and object literalsUse array and object literals instead of statement-by-statement assignment.
var values = new Array();values[0] = 123;values[1] = 456;values[2] = 789;//After improvement, var values = [123, 456, 789];var person = new Object();person.name = Jack;person.age = 28;person.sayName = function(){ alert(this.name);};//After improvement var person = { name : Jack, age : 28, sayName : function(){ alert(this.name); }};String optimization String concatenationEarly browsers did not optimize the way of concatenating strings with the plus sign. Since 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!;Add the string to the array, and then call the join method of the array to convert it to a string, thus avoiding the use of the addition operator.
var arr = [], i = 0;arr[i++] = Hello;arr[i++] = ;arr[i++] = World!;var text = arr.join('');Modern browsers have optimized string plus sign concatenation, so in most cases, the addition operator is still the first choice.
Reduce reflows and redrawsIn the browser rendering process, reflow and redraw are involved, which is a process that consumes performance. You should pay attention to reducing the actions that trigger reflow and redraw during script operations.
What operations trigger reflow or redraw?
- Reflow: The geometric properties of the element have changed and the rendering tree needs to be rebuilt. The process of changing the rendering tree is called reflow;
- Redraw: The geometric size of the element has not changed, but the CSS style (background color or color) of an element has changed.
How to reduce reflow and redraw and improve web page performance?
- Resize window
- Modify font
- Add or remove style sheets
- Content changes, such as the user entering text in the <input/> box
- Manipulate class attributes
- Scripts to manipulate DOM (add, delete or modify DOM elements)
- Calculate offsetWidth and offsetHeight properties
- Set the value of the style attribute
1. Script manipulation of DOM elements
- Set the DOM element to display:none. A reflow will be triggered during the setting process, but you can change it at will later and display it after modification;
- Clone the element into memory before operating it, and replace the element again after modification.
2. Modify the style of the element
- Try to make batch modifications instead of modifying them one by one;
- Set the id and class in advance, and then set the className of the element.
3. When adding animation to an element, set the CSS style of the element to position:fixed or position:absolute. The element will not cause reflow after it leaves the document flow.
4. Use the throttling function (already mentioned above) when adjusting the window size, inputting in the input box, scrolling the page, etc.
HTTP browser cacheProperly setting browser cache is one of the important means of web page optimization.
Expires and Cache-ControlExpires comes from HTTP1.0, and Cache-Control comes from HTTP1.1. When both are set at the same time, Cache-Control will override Expires.
ETag and Last-Modified
- Expires specifies the actual expiration date rather than the number of seconds. But Expires has some problems, such as server time being out of sync or inaccurate. So it's better to express expiration time using remaining seconds rather than absolute time.
- Cache-Control can set the max-age value in seconds and specify the cache expiration time. For example: Cache-Control: max-age=3600.
Both ETag and Last-Modified are returned by the server in the response headers. ETag has a higher priority than Last-Modified, which means that the server will prioritize the value of ETag.
Strong caching and negotiated caching
- ETag is any tag attached to the document, which may be the serial number or version number of the document, or the verification of the document content, etc. When the document changes, the ETag value also changes. Related to ETag is If-None-Match. When the browser initiates a request, it will carry the ETag value in the If-None-Match field and send it to the server;
- Last-Modified is the time when the document was last modified on the server side. Related to Last-Modified is If-Modified-Since. When the browser initiates a request, it will carry the value of Last-Modified in the If-Modified-Since field and send it to the server.
The types of cache are strong cache and negotiated cache. The difference between the two is that the strong cache will not send a request to the server, but the negotiated cache will send a request. If the match is successful, it will return 304 Not Modified, if the match is unsuccessful, it will return 200; the browser will first verify the strong cache, and if the strong cache misses, then Perform negotiation cache verification.
How to configure browser cacheWhy reduce HTTP requests
- Add Expires and Cache-Control to the return response of the web server;
- Configure Expires and Cache-Control in the nginx or apache configuration file.
Measures to reduce http requests account for a large part in performance optimization, such as: using css sprite images to replace multiple image requests, avoiding empty src images, using inline images, using external link css and js, caching, etc.
The process from entering the URL to completing the page loading includes:
- DNS resolution
- TCP connection
- HTTP request and response
- Browser renders page
- close connection
A complete http request has to go through these processes, which is time-consuming and resource-consuming, so it becomes necessary to reduce the number of requests.
References:
"Advanced Guide to High-Performance Website Construction vs. High-Performance Website Construction"
"Best Practices for Speeding Up Your Web Site"
The above is the entire content of this article. I hope it will be helpful to everyone’s study. I also hope everyone will support VeVb Wulin Network.