Home > Article > Web Front-end > Summary of methods for page performance optimization
The Internet has a famous 8-second principle. When users access a Web page, they will become impatient if it takes more than 8 seconds. If it takes too long to load, they will give up visiting . Most users expect web pages to load within 2 seconds. In fact, for every extra second in load time, you lose 7% of your users. 8 seconds is not exactly 8 seconds, it just shows the importance of loading time to website developers. So how do we optimize page performance and improve page loading speed? This is the main issue to be discussed in this article. However, performance optimization is a comprehensive issue. There is no standard answer. It is not easy to list everything comprehensively. This article only focuses on some core points. The following is my summary of common methods for performance optimization:
Mainly include these aspects:html compression, css compression, js Compression and shuffling and file merging.
Resource compression can remove redundant characters from files, such as carriage returns and spaces. When you write code in an editor, you use indentation and comments. These methods undoubtedly make your code concise and readable, but they also add extra bytes to the document.
html code compression is to compress characters that are meaningful in text files but not displayed in HTML, including spaces, tabs, newlines, etc. Characters with some other meanings, such as HTML comments, can also be compressed.
How to compress html:
Use an online website for compression (generally not used during development)
nodejs provides the html-minifier tool
Back-end template engine rendering compression
css code compression is simply invalid code deletion and css semantic merging
How to compress css:
Use online websites for compression (Generally not used during development)
Use html-minifier tool
Use clean-css to compress css
The compression and confusion of js mainly include the following parts:
Deletion of invalid characters
Removal of comments
How to compress and confuse js
In fact, the compression and confusion of css compression and js are much greater than the benefits of html compression. At the same time, the ratio of css code and js code is There are much more html codes, and the reduction in traffic brought about by css compression and js compression will be very obvious. So for large companies, html compression is optional, but css compression and js compression and confusion are a must!
4. File merge
##As can be seen from the above figure, there are no merge requests The following shortcomings:
. So how to deal with this problem? ----Public library merging and merging of different pages.
How to merge files
① async method
<script></script>
如果是多个脚本,该方法可以确保所有设置了defer属性的脚本按顺序执行
如果脚本不会改变文档的内容,可将defer属性加入到script标签中,以便加快处理文档的速度
③动态创建script标签
在还没定义defer和async前,异步加载的方式是动态创建script,通过window.onload方法确保页面加载完毕再将script标签插入到DOM中,具体代码如下:
function addScriptTag(src){ var script = document.createElement('script'); script.setAttribute("type","text/javascript"); script.src = src; document.body.appendChild(script); } window.onload = function(){ addScriptTag("js/index.js"); }
1)defer是在HTML解析完之后才会执行,如果是多个,按照加载的顺序依次执行
2)async是在加载完之后立即执行,如果是多个,执行顺序和加载顺序无关
其中蓝色线代表网络读取,红色线代表执行时间,这俩都是针对脚本的;绿色线代表 HTML 解析。
对于web应用来说,缓存是提升页面性能同时减少服务器压力的利器。
1.强缓存:不会向服务器发送请求,直接从缓存中读取资源,在chrome控制台的network选项中可以看到该请求返回200的状态码,并且size显示from disk cache或from memory cache;
Expires :response header里的过期时间,浏览器再次加载资源时,如果在这个过期时间内,则命中强缓存。它的值为一个绝对时间的GMT格式的时间字符串, 比如Expires:Thu,21 Jan 2018 23:39:02 GMT
Cache-Control :这是一个相对时间,在配置缓存的时候,以秒为单位,用数值表示。当值设为max-age=300时,则代表在这个请求正确返回时间(浏览器也会记录下来)的5分钟内再次加载资源,就会命中强缓存。比如Cache-Control:max-age=300,
简单概括:其实这两者差别不大,区别就在于 Expires 是http1.0的产物,Cache-Control是http1.1的产物,两者同时存在的话,Cache-Control优先级高于Expires;在某些不支持HTTP1.1的环境下,Expires就会发挥用处。所以Expires其实是过时的产物,现阶段它的存在只是一种兼容性的写法。强缓存判断是否缓存的依据来自于是否超出某个时间或者某个时间段,而不关心服务器端文件是否已经更新,这可能会导致加载文件不是服务器端最新的内容,那我们如何获知服务器端内容较客户端是否已经发生了更新呢?此时我们需要协商缓存策略。
2.协商缓存:向服务器发送请求,服务器会根据这个请求的request header的一些参数来判断是否命中协商缓存,如果命中,则返回304状态码并带上新的response header通知浏览器从缓存中读取资源;另外协商缓存需要与cache-control共同使用。
①Last-Modified和If-Modified-Since:当第一次请求资源时,服务器将资源传递给客户端时,会将资源最后更改的时间以“Last-Modified: GMT”的形式加在实体首部上一起返回给客户端。
Last-Modified: Fri, 22 Jul 2016 01:47:00 GMT
客户端会为资源标记上该信息,下次再次请求时,会把该信息附带在请求报文中一并带给服务器去做检查,若传递的时间值与服务器上该资源最终修改时间是一致的,则说明该资源没有被修改过,直接返回304状态码,内容为空,这样就节省了传输数据量 。如果两个时间不一致,则服务器会发回该资源并返回200状态码,和第一次请求时类似。这样保证不向客户端重复发出资源,也保证当服务器有变化时,客户端能够得到最新的资源。一个304响应比一个静态资源通常小得多,这样就节省了网络带宽。
但last-modified 存在一些缺点:
Ⅰ.某些服务端不能获取精确的修改时间
Ⅱ.文件修改时间改了,但文件内容却没有变
既然根据文件修改时间来决定是否缓存尚有不足,能否可以直接根据文件内容是否修改来决定缓存策略?----ETag和If-None-Match
②ETag and If-None-Match: Etag is the response header returned by the server when the resource was last loaded. It is a unique identification of the resource. As long as the resource changes, Etag will be reset. generate. When the browser loads resources and sends a request to the server next time, it will put the Etag value returned last time into the If-None-Match in the request header. The server only needs to compare the If-None-Match sent by the client with its own server. Whether the ETag of the resource is consistent can be used to determine whether the resource has been modified relative to the client. If the server finds that the ETag does not match, it will directly send the new resource (including the new ETag) to the client in the form of a regular GET 200 return packet; if the ETag is consistent, it will directly return 304 to notify the client directly. Just use local cache.
Comparison between the two:
First of all, in terms of accuracy, Etag is better than Last-Modified. The time unit of Last-Modified is seconds. If a file changes multiple times within 1 second, then their Last-Modified does not actually reflect the modification, but the Etag will change every time to ensure accuracy; if it is load-balanced Server, the Last-Modified generated by each server may also be inconsistent.
Secondly, in terms of performance, Etag is inferior to Last-Modified. After all, Last-Modified only needs to record time, while Etag requires the server to calculate a hash value through an algorithm.
Third, in terms of priority, server verification gives priority to Etag
Forced caching takes precedence over negotiated caching. If forced If the cache (Expires and Cache-Control) is effective, the cache will be used directly. If it is not effective, the cache will be negotiated (Last-Modified / If-Modified-Since and Etag / If-None-Match). The negotiated cache will be decided by the server whether to use the cache. If the negotiated cache is invalid, then the cache for the request is invalid, the request result is re-obtained, and then stored in the browser cache; if it takes effect, 304 will be returned and the cache will continue to be used . The main process is as follows:
1. Address bar access, link jump is normal User behavior will trigger the browser cache mechanism;
2.F5 refresh, the browser will set max-age=0, skip strong cache judgment, and negotiate cache judgment;
3.ctrl F5 refresh, skip the strong cache and negotiated cache, and pull resources directly from the server.
If you want to know more about the caching mechanism, please click In-depth understanding of the browser’s caching mechanism
Large Web applications The pursuit of speed does not stop at just using the browser cache, because the browser cache is always only to improve the speed of the second visit. For the acceleration of the first visit, we need to optimize from the network level. The most common method is CDN (Content Delivery). Network, content delivery network) acceleration. By caching static resources (such as javascript, css, pictures, etc.) to the CDN node of the same network operator that is very close to the user, it can not only improve the user's access speed, but also save the server's bandwidth consumption and reduce load.
In fact, this is a CDN service provider deploying computing nodes in various provinces across the country. CDN acceleration caches website content at the edge of the network. Users in different regions will access the CDN nodes on the same network line closest to them. , when the request reaches the CDN node, the node will determine whether its content cache is valid. If it is valid, it will immediately respond to the cached content to the user, thereby speeding up the response speed. If the cache of the CDN node fails, it will go to our content source server according to the service configuration to obtain the latest resource response to the user, and cache the content to respond to subsequent users. Therefore, as long as one user in a region loads the resource first and establishes a cache in the CDN, other subsequent users in the region can benefit from this .
Resource preloading is another performance optimization technology. We can use this technology to inform the browser in advance that certain resources may be used in the future. .
Through DNS pre-resolution, we tell the browser that we may obtain resources from a specific URL in the future. When the browser actually uses a resource in this domain, DNS resolution can be completed as quickly as possible. For example, if we can get image or audio resources from example.com in the future, we can add the following content to the
<link>
当我们从该 URL 请求一个资源时,就不再需要等待 DNS 的解析过程。该技术对使用第三方资源特别有用。通过简单的一行代码就可以告知那些兼容的浏览器进行 DNS 预解析,这意味着当浏览器真正请求该域中的某个资源时,DNS 的解析就已经完成了,从而节省了宝贵的时间。
另外需要注意的是,浏览器会对a标签的href自动启用DNS Prefetching,所以a标签里包含的域名不需要在head中手动设置link。但是在HTTPS下不起作用,需要meta来强制开启功能。这个限制的原因是防止窃听者根据DNS Prefetching推断显示在HTTPS页面中超链接的主机名。下面这句话作用是强制打开a标签域名解析
<meta>
The above is the detailed content of Summary of methods for page performance optimization. For more information, please follow other related articles on the PHP Chinese website!