Summary of page optimization methods
This time I will bring you a summary of page optimization methods, what are the precautions for page optimization, the following is a practical case, let’s take a look.
Background Purpose
Let the official website homepage load faster, respond to user operations more promptly, and provide users with a more friendly experience.
Reduce the number of page requests, reduce the bandwidth occupied by requests, and save resources.
Optimization means
Divided into two categories according to granularity:
Page level optimization (number of HTTP requests, resource consolidation and compression , resource loading timing, etc.)
Code level optimization (DOM operation optimization, CSS selector optimization, HTML structure optimization)
Specific measures
Page Level Optimization
The page level optimization goal is basically how to reduce the number of HTTP requests and reduce the volume of requested resources. Each request has a cost, including both time cost and resource cost (a complete request requires a "long" process such as DNS addressing, establishing a connection with the server, sending data, waiting for the server to respond, and receiving data. Complex process)
1. Merging and compressing static resources
According to the type of static files, you can use the gulp tool to merge and compress js files and css files.
For example, there are seven css files and more than ten or twenty js files in the official website project. After merging and compressing the static resources, the HTTP overhead can be reduced.
We merge and compress all resources that do not change frequently (such as jquery, various lib libraries, plug-ins, etc.) into one file, named vender.css, vender.js. Files that are frequently changed online are merged and compressed into one file, named index.css, index.js, and added with hash stamps. The contents of index and other files will basically change every time they are online, so the hash added after gulp is automatically built The poke is also different, but the render type remains the same, so we can make reasonable use of the browser's caching mechanism.
2. Image processing
Use jq’s
lazyload
plug-in to implement lazy loading of images. Wait for the scroll bar to scroll to the corresponding place before loading the required image resources.Instead of directly using the double image provided by the design, use
devicePixelRatio
of css to check the pixel ratio of the device to assist in distinguishing between retina devices and non-retina devices to decide whether to load the two. The doubled image is still the original size image.Before uploading the image to cdn, use the
gulp-imagemin
tool to compress the size without distortion.Make all small pictures like the picture below into sprite pictures. You can consider using
icon-font
to achieve monochrome. Or you can write svg code directly on the page and convert it to base64 and write it to the page. In short, you need to reduce the number of http requests.
3. First screen loading
Present the first screen to the user immediately.
The specific method is to wrap all the DOM elements with a template
element except for the first screen DOM element. After the window monitors the load event, all the remaining DOM parts are inserted into the page. middle. (Tips: To prevent users from starting to scroll the page before waiting for the window's load event, you can expand the range of the first screen.)
4. DNS pre-reading
DNS pre-reading It is a function that enables the browser to actively perform domain name resolution. DNS requests require very little bandwidth, but the latency is a bit high.
The following is a quote from MDN:
In some browsers this prefetching behavior will occur in parallel with the actual content of the page (rather than serially). Because of this, the resolution process of some high-latency domain names will not block the loading of resources.
This can greatly speed up page loading (especially in mobile network environments). In some pages with many images, pre-resolving the domain name before initiating an image loading request will increase the image loading speed by at least 5%.
Specific method: head
Add
<link rel="dns-prefetch" href="https://data.dadaabc.com/">
data.dadaabc.com
to the tag as the domain name of the static resource, if there are other The linked domain names are all added together.
5. 多域名分发静态资源
同域下浏览器能并发的请求有限,为了增加并发,尤其是一些静态资源上,可以使用多个域名。但由于域名DNS解析本身也是耗时的,所以也不是越多越好,chrome最大支持6路并发,所以一般设置2-4个域名较为合适。
具体的做法是:再增加cdn域名来下载静态资源。比如图片全部用img.dadaabc.com/
域名,css资源全部用css.dadaabc.com/
域名,这些域名最终全部指向同样的cdn服务器。静态资源域名加前缀可以用gulp-rev-replace
来实现。
6. 统计代码
统计代码全部放到window的load事件之后执行。为了便于管理统计代码,例如页面加上一些埋点,增加删除统计产品,我们可以借助Google Tag Manager
工具来统一管理。
具体做法是:页面只拉取Google Tag Manager
提供的gtm
代码,该js代码含有全部的统计产品,例如百度、Inspelect等, 这些统计产品也都是通过创建script标签来动态插入到页面中的。另外需要注意的是,google提供的gtm
代码是在google服务器上的,为了让获取该代码的速度更快,我们可以在自己的服务器上执行crontab
定时任务,每分钟获取一次,然后gtm
代码直接从自己服务器上获取。
代码级别优化
1. 合理的dom结构
css文件全部放到head
里,script文件全部放到body
的最底部。
原因:
把样式表移到head
里允许页面逐步渲染。
浏览器负责渲染的GUI渲染线程与JS引擎线程是互斥的,当JS引擎执行时GUI线程会被挂起(相当于被冻结了),GUI更新会被保存在一个队列中等到JS引擎空闲时立即被执行。
参考资料:从浏览器多进程到JS单线程,JS运行机制最全面的一次梳理
2. 最小化重排和重绘
多个属性改变一次性写:
举个例子:
var ele = document.getElementById('myp'); ele.style.borderLeft = '1px'; ele.style.borderRight = '2px'; ele.style.padding = '5px';
三个样式属性被改变,每一个都会影响元素的几何结构,虽然大部分现代浏览器都做了优化,只会引起一次重排,但是像上文一样,如果一个及时的属性被请求,那么就会强制刷新队列,而且这段代码四次访问DOM,一个很显然的优化策略就是把它们的操作合成一次,这样只会修改DOM一次:
var ele = document.getElementById('myp'); ele.style.cssText = 'border-left: 1px; border-right: 2px; padding: 5px;';
总结:同一个DOM的多个属性改变可以写在一起(减少DOM访问,同时把强制渲染队列刷新的风险降为0)
fragment元素的应用:
fragment是个轻量级的document对象,它的设计初衷就是为了完成更新和移动节点这样的任务。fragment的一个便利的语法特性是当你附加一个片断到节点时,实际上被添加的是该片断的子节点,而不是片断本身。只触发了一次重排,而且只访问了一次实时的DOM。
例如:
var fragment = document.createDocumentFragment(); var li = document.createElement('li'); li.innerHTML = 'apple'; fragment.appendChild(li); var li = document.createElement('li'); li.innerHTML = 'watermelon'; fragment.appendChild(li); document.getElementById('fruit').appendChild(fragment);
3. 函数防抖和函数节流
触发大量回调函数的事件,例如拖拽时的mousemove
事件,window对象的resize
、scroll
事件,文字输入、自动完成的keyup
事件等,需要合理使用函数防抖和函数节流机制。具体可以参考我的另外一篇文章函数防抖和函数节流
4. CSS选择器
CSS选择器的解析式其实是从右到左的,例如:
#p1 a { color: red }
如上面的选择器,浏览器必须遍历查找所有的a元素,再去找ID为p1的元素,这样查找的方式显然很低效。
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
Detailed explanation of the use of component communication in React
The above is the detailed content of Summary of page optimization methods. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Unfortunately, people often delete certain contacts accidentally for some reasons. WeChat is a widely used social software. To help users solve this problem, this article will introduce how to retrieve deleted contacts in a simple way. 1. Understand the WeChat contact deletion mechanism. This provides us with the possibility to retrieve deleted contacts. The contact deletion mechanism in WeChat removes them from the address book, but does not delete them completely. 2. Use WeChat’s built-in “Contact Book Recovery” function. WeChat provides “Contact Book Recovery” to save time and energy. Users can quickly retrieve previously deleted contacts through this function. 3. Enter the WeChat settings page and click the lower right corner, open the WeChat application "Me" and click the settings icon in the upper right corner to enter the settings page.

Tomato Novel is a very popular novel reading software. We often have new novels and comics to read in Tomato Novel. Every novel and comic is very interesting. Many friends also want to write novels. Earn pocket money and edit the content of the novel you want to write into text. So how do we write the novel in it? My friends don’t know, so let’s go to this site together. Let’s take some time to look at an introduction to how to write a novel. Share the Tomato novel tutorial on how to write a novel. 1. First open the Tomato free novel app on your mobile phone and click on Personal Center - Writer Center. 2. Jump to the Tomato Writer Assistant page - click on Create a new book at the end of the novel.

Mobile games have become an integral part of people's lives with the development of technology. It has attracted the attention of many players with its cute dragon egg image and interesting hatching process, and one of the games that has attracted much attention is the mobile version of Dragon Egg. To help players better cultivate and grow their own dragons in the game, this article will introduce to you how to hatch dragon eggs in the mobile version. 1. Choose the appropriate type of dragon egg. Players need to carefully choose the type of dragon egg that they like and suit themselves, based on the different types of dragon egg attributes and abilities provided in the game. 2. Upgrade the level of the incubation machine. Players need to improve the level of the incubation machine by completing tasks and collecting props. The level of the incubation machine determines the hatching speed and hatching success rate. 3. Collect the resources required for hatching. Players need to be in the game

Setting font size has become an important personalization requirement as mobile phones become an important tool in people's daily lives. In order to meet the needs of different users, this article will introduce how to improve the mobile phone use experience and adjust the font size of the mobile phone through simple operations. Why do you need to adjust the font size of your mobile phone - Adjusting the font size can make the text clearer and easier to read - Suitable for the reading needs of users of different ages - Convenient for users with poor vision to use the font size setting function of the mobile phone system - How to enter the system settings interface - In Find and enter the "Display" option in the settings interface - find the "Font Size" option and adjust it. Adjust the font size with a third-party application - download and install an application that supports font size adjustment - open the application and enter the relevant settings interface - according to the individual

In today's society, mobile phones have become an indispensable part of our lives. As an important tool for our daily communication, work, and life, WeChat is often used. However, it may be necessary to separate two WeChat accounts when handling different transactions, which requires the mobile phone to support logging in to two WeChat accounts at the same time. As a well-known domestic brand, Huawei mobile phones are used by many people. So what is the method to open two WeChat accounts on Huawei mobile phones? Let’s reveal the secret of this method. First of all, you need to use two WeChat accounts at the same time on your Huawei mobile phone. The easiest way is to

The difference between Go language methods and functions lies in their association with structures: methods are associated with structures and are used to operate structure data or methods; functions are independent of types and are used to perform general operations.

Time complexity measures the execution time of an algorithm relative to the size of the input. Tips for reducing the time complexity of C++ programs include: choosing appropriate containers (such as vector, list) to optimize data storage and management. Utilize efficient algorithms such as quick sort to reduce computation time. Eliminate multiple operations to reduce double counting. Use conditional branches to avoid unnecessary calculations. Optimize linear search by using faster algorithms such as binary search.

Mobile phone film has become one of the indispensable accessories with the popularity of smartphones. To extend its service life, choose a suitable mobile phone film to protect the mobile phone screen. To help readers choose the most suitable mobile phone film for themselves, this article will introduce several key points and techniques for purchasing mobile phone film. Understand the materials and types of mobile phone films: PET film, TPU, etc. Mobile phone films are made of a variety of materials, including tempered glass. PET film is relatively soft, tempered glass film has good scratch resistance, and TPU has good shock-proof performance. It can be decided based on personal preference and needs when choosing. Consider the degree of screen protection. Different types of mobile phone films have different degrees of screen protection. PET film mainly plays an anti-scratch role, while tempered glass film has better drop resistance. You can choose to have better
