Front-end performance optimization record

   For the front-end, fast means requiring smaller resources, more streamlined quantities, earlier presentation of content, and more user-friendly interactions. When the project achieves a certain level, performance should be considered. There are many theories and methods for front-end performance optimization, such as Yahoo! Performance Military, Google PageSpeed ​​Insights Rules. 

   For example, it takes about 20 seconds to load the first screen of an older project, which seriously affects the user experience, so it is necessary to perform a performance optimization of the first screen loading. 

 

browser rendering process 

First of all, let's have a little understanding of the rendering process after the browser receives resources such as HTML/CSS/JavaScript:

   After the browser receives the HTML document, it parses the document and starts to build the DOM (Document Object Model) tree, then finds the style sheet in the document, and starts to parse the CSS to build the CSSOM (CSS Object Model) tree, both of which are completed. After that, start building the render tree.

   The DOM tree describes the structure and content of the document, and the CSSOM tree describes the style rules applied to the document. To render a page, you need to combine the DOM tree with the CSSOM tree, which is the rendering tree. After the rendering tree is built, the browser gets the content and style of each visible node. The next step is to calculate the exact position and size of each node in the window, which is the layout phase. When the Layout layout event is completed, the browser will immediately issue the Paint Setup and Paint events, and start to draw the rendering tree into pixels. The time required for drawing is proportional to the complexity of the CSS style. After the drawing is completed, the user can see the page. the final rendering effect. 

   When building the DOM tree in the above figure, the <script> tag may block HTML parsing, thus affecting the loading speed of the home page. You can use async for asynchronous loading or defer for lazy loading. 

   The async attribute means that the script will be executed as soon as possible after downloading, but there is no guarantee that the script will be executed in order. 

   The defer attribute indicates that the script will be downloaded first, but will be run after the entire page has been parsed, and executed in the order in which the scripts appear.

The difference between the two can be clearly seen with a picture on the Internet:

            The blue line represents network reads, the red line represents execution time, both of which are for scripts; the green line represents HTML parsing

Using these two properties can solve the slow loading problem caused by <script>

 

Reduce unnecessary HTML tags 

   From the process of browser rendering, it can be seen that if there are many unnecessary tags in HTML, it will affect the DOM parsing speed and increase the size of the HTML file. The deeply nested structure can be optimized to remove unnecessary tags.

 

reduce CSS nesting 

   If CSS is nested too deeply, it will affect the speed at which the browser finds the selector. To a certain extent, a lot of redundant bytes are produced. Generally, it is nested at most 3 layers.

 

Enable CSS Sprite 

   CSS Sprites are called css sprites by many people in China, and are a kind of web page image application processing method. It allows you to include all the sporadic pictures involved in a page into a large picture, so that when visiting the page, the loaded pictures will not be displayed slowly one by one as before . 

   There are three svg pictures on the home page of the project. Refer to SVG Sprite to perform simple svg sprite processing on these three pictures. In angular/cli, you can also refer to this SVG icon system with angular-cli for the svg pictures in the project. Unified processing. 

   When processing css sprites, pay attention to the following points: 

① Merge the picture horizontally, so that the picture size is smaller

② The spacing should not be too large, which has little effect on the image size, but requires less memory when decompressing the client

③After css sprite processing, the number of home page resource requests is reduced. 

For icon-like images, it is best to use iconfont to reduce additional requests for images. 

 

Compress static resources 

   The combined and packaged js, css, and image files are generally larger in size, and they should be compressed at this time. Both gulp and webpack have corresponding compression plugins. 

For individual pictures, sometimes they can be taken out separately for processing, and you can go to tinypng for online compression.

 

Preloading with lazyload and preloading

   In Angular, you can use loadChildren to implement lazyload in routing, which can achieve on-demand loading and speed up loading

{  
  path: 'home',  
  loadChildren: 'app/home/home.module#HomeModule',  
},  

   首页显示的模块不应该过大,我们项目中首页加载的模块虽然使用了lazyload,但是模块太大,以至于严重影响了加载速度,于是对模块进行了切割,分成2个模块,对于第二个模块进行了preloading,这样在首页加载完毕后,会对该模块进行预加载,加快了路由切换时的速度。关于preloading可以参考Angular官网的自定义预加载策略。 

 

Nginx启用Gzip压缩 

   HTTP协议上的gzip编码是一种用来改进web应用程序性能的技术,web服务器和客户端(浏览器)必须共同支持gzip。目前主流的浏览器,Chrome,firefox,IE等都支持该协议。常见的服务器如Apache,Nginx,IIS同样支持gzip。 

   gzip压缩比率在3到10倍左右,可以大大节省服务器的网络带宽。而在实际应用中,并不是对所有文件进行压缩,通常只是压缩静态文件。 

   在Nginx中,启用gzip: 

# 开启gzip  
    gzip on;  
    # 启用gzip压缩的最小文件,小于设置值的文件将不会压缩  
    gzip_min_length 1k;  
    # gzip 压缩级别,1-10,数字越大压缩的越好,也越占用CPU时间  
    gzip_comp_level 5;  
    # 进行压缩的文件类型。javascript有多种形式。其中的值可以在 mime.types 文件中找到。  
    gzip_types   
        application/atom+xml  
        application/javascript  
        application/json  
        application/ld+json  
        application/manifest+json  
        application/rss+xml  
        application/vnd.geo+json  
        application/vnd.ms-fontobject  
        application/x-font-ttf  
        application/x-web-app-manifest+json  
        application/xhtml+xml  
        application/xml  
        font/opentype  
        image/bmp  
        image/svg+xml  
        image/x-icon  
        text/cache-manifest  
        text/css  
        text/plain  
        text/vcard  
        text/vnd.rim.location.xloc  
        text/vtt  
        text/x-component  
        text/x-cross-domain-policy;  
    # 是否在http header中添加Vary: Accept-Encoding,建议开启  
    gzip_vary on;  
    # 禁用IE 6 gzip  
    gzip_disable "MSIE [1-6]\.";  

 不同gzip_comp_level的压缩率可以参考下图: 

   gzip对svg和x-icon的压缩效果比较明显,一般可以达到50%以上的压缩效果,但是对于压缩过的PNG、GIF格式图片启用Gzip,反而会因为添加标头、压缩字典,增大了图片的大小。 

   启用压缩后,首页请求的资源大小由原来的10M降低到2.8M,效果还是比较明显的。

 

启用http缓存 

   每次访问网页时80%的时间都会花在资源下载上,因此使用缓存可以大大提高网页访问时的响应速度。 

   参考H5BP配置目录下的expires.conf,作为Nginx服务器配置: 

# Expire rules for static content  
# No default expire rule. This config mirrors that of apache as outlined in the  
# html5-boilerplate .htaccess file. However, nginx applies rules by location,  
# the apache rules are defined by type. A consequence of this difference is that  
# if you use no file extension in the url and serve html, with apache you get an  
# expire time of 0s, with nginx you'd get an expire header of one month in the  
# future (if the default expire rule is 1 month). Therefore, do not use a  
# default expire rule with nginx unless your site is completely static  
# cache.appcache, your document html and data  
location ~* \.(?:manifest|appcache|html?|xml|json)$ {  
  add_header Cache-Control "max-age=0";  
}  
# Feed  
location ~* \.(?:rss|atom)$ {  
  add_header Cache-Control "max-age=3600";  
}  
# Media: images, icons, video, audio, HTC  
location ~* \.(?:jpg|jpeg|gif|png|ico|cur|gz|svg|mp4|ogg|ogv|webm|htc)$ {  
  access_log off;  
  add_header Cache-Control "max-age=2592000";  
}  
# Media: svgz files are already compressed.  
location ~* \.svgz$ {  
  access_log off;  
  gzip off;  
  add_header Cache-Control "max-age=2592000";  
}  
# CSS and Javascript  
location ~* \.(?:css|js)$ {  
  add_header Cache-Control "max-age=31536000";  
  access_log off;  
}  
# WebFonts  
# If you are NOT using cross-domain-fonts.conf, uncomment the following directive  
# location ~* \.(?:ttf|ttc|otf|eot|woff|woff2)$ {  
#  add_header Cache-Control "max-age=2592000";  
#  access_log off;  
# }  

    上述配置禁用manifest,appcache,html,xml和json文件的缓存。 它将RSS和ATOM订阅文件缓存1小时,   Javascript和CSS文件1年,以及其他静态文件(图像和媒体)1个月。 

缓存全部设置为public,所以任何系统都可以缓存它们。 将它们设置为私有将限制它们被私有缓存(例如我们的浏览器)缓存。 

   关于缓存中资源的新鲜度控制可以看这篇文章HTTP缓存控制小结。 

 

总结 

   这次只是很简单地对首屏加载进行了性能优化,减少了10个http请求,总资源大小从10.4MB降到2.8MB,首屏DOMContentLoaded时间从12秒左右降到2秒左右,load时间从22秒左右降到6秒左右,效果还是很明显的。

 

 

 

 

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326168805&siteId=291194637