search
HomeWeb Front-endCSS TutorialBasic performance optimization of front-end web pages

Basic performance optimization of front-end web pages

Jun 13, 2018 pm 02:17 PM
Web page performance optimization

This time I will bring you the basic performance optimization of front-end web pages. What are the precautions? The following is a practical case, let’s take a look.

Page optimization

Static resource compression

Use the appropriate build tools (webpack, gulp) Compress web page static resources such as images, scripts and styles.

CSS sprite image, base64 inline image

Merge the small icons in the site into one image, use css positioning to intercept the corresponding icon; use inline images appropriately.

Style on top, script on bottom

The page is a gradual rendering process, style on top can present the page to the user faster; <script> tag on top will block Download resources at the back of the page. </script>

Use external link css and js

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

Avoid empty src images

Avoid unnecessary http requests.

<!-- 空src的图片依然会发起http请求 -->
<img  src="/static/imghwm/default1.png" data-src="" class="lazy" alt="Basic performance optimization of front-end web pages" >

Avoid scaling images in html

Try to use the specified size for images as needed, rather than loading a large image and then reducing it.

<!-- 实际图片尺寸为600x300,在html中缩放为了200x100 -->
<img  src="/static/imghwm/default1.png" data-src="/static/images/a.png" class="lazy" alt="Basic performance optimization of front-end web pages" >

Preload preloading

Setting the preload attribute on the rel of the link tag allows the browser to preload resources before the main rendering mechanism intervenes. This mechanism can obtain resources earlier and does not block the initialization of the page.

nbsp;html>


  <meta>
  <title>Document</title>
  <link>
  <link>
  
  <link>


  
  <script></script>

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

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

  1. style

  2. script

  3. ##video

  4. audio

  5. ##image
  6. font
  7. ##document
  8. ...
  9. This method can also preload resources across domains, just set the crossorigin attribute.
  10. <link>

CSS

Selector

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

##ID Selector

  1. Class Selector

  2. Tag Selector

  3. Adjacent selector

  4. 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.

  5. 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

Experience in using selectors:

Give priority to class selectors, which can replace multi-layer label selectors;

  1. Use with caution ID selector, although it is efficient, is unique in the page, which is not conducive to team collaboration and maintenance;

  2. Make reasonable use of the inheritance of the selector;

  3. Avoid css expressions.

  4. Reduce the level of selectors

Based on the priority of the previous selector, multi-level selector embedding should be avoided as much as possible. It is best not to exceed 3 layers.

.container .text .logo{ color: red; }
/*改成*/
.container .text-logo{ color: red; }

Streamline page style files and remove unused styles

The browser will perform redundant style matching, which will affect rendering time. In addition, too large style files will also affect loading. speed.

Use css inheritance to reduce the amount of code

Using the inheritable attributes 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 is added to reduce the amount of code.

.text{ width: 0px; height: 0px; }
/*改成*/
.text{ width: 0; height: 0; }

JavaScript

使用事件委托

给多个同类DOM元素绑定事件使用事件委托。


      
  • 1
  •   
  • 2
  •   
  • 3
// 不合理的方式:给每个元素都绑定click事件
$('#container .list').on('click', function() {
  var text = $(this).text();
  console.log(text);
});
// 事件委托方式:利用事件冒泡机制将事件统一委托给父元素
$('#container').on('click', '.list', function() {
  var text = $(this).text();
  console.log(text);    
});

需要注意的是,虽然使用事件委托时都可以将事件委托给document来做,但这是不合理的,一个是容易造成事件误判,另一个是作用域链查找效率低。应该选择最近的父元素作为委托对象。

使用事件委托除了性能上更优,动态创建的DOM元素也不需要再绑定事件。

DOMContentLoaded

可在DOM元素加载完毕(DOMContentLoaded)后开始处理DOM树,不必等到所有图片资源下载完后再处理。

// 原生javascript
document.addEventListener("DOMContentLoaded", function(event) {
  console.log("DOM fully loaded and parsed");
}, false);
// jquery
$(document).ready(function() {
  console.log("ready!");
});
// $(document).ready()的简化版
$(function() {
  console.log("ready!");
});

预加载和懒加载

预加载

利用浏览器空闲时间预先加载将来可能会用到的资源,如图片、样式、脚本。

无条件预加载

一旦onload触发,立即获取将来需要用到的资源。

图片资源预加载。(3种实现图片预加载的方式)。

基于用户行为的预加载

对于用户行为可能进行的操作进行判断,预先加载将来可能需要用到的资源。

  1. 当用户在搜索输入框输入时,预先加载搜索结果页可能用到的资源;

  2. 当用户去操作一个Tab选项卡时,默认显示其中一个,当要去点击(click)其他选项时,在鼠标hover时,就可先加载将来会用到的资源;

懒加载

除页面初始化需要的内容或组件之外,其他都可以延迟加载,如剪切图片的js库、不在可视范围的图片等等。

图片懒加载。(判断图片是否在可视区域范围内,若在,则将真实路径赋给图片)

避免全局查找

任何一个非局部变量在函数中被使用超过一次时,都应该将其存储为局部变量。

function updateUI(){
  var imgs = document.getElementsByTagName("img");
  for (var i=0, len=imgs.length; i <p style="text-align: left;">在上面函数中多次使用到document全局变量,尤其在for循环中。因此将document全局变量存储为局部变量再使用是更优的方案。</p><pre class="brush:php;toolbar:false">function updateUI(){
  var doc = document;
  var imgs = doc.getElementsByTagName("img");
  for (var i=0, len=imgs.length; i <p style="text-align: left;">值得注意的一点是,在javascript代码中,任何没有使用var声明的变量都会变为全局变量,不正当的使用会带来性能问题。</p><p style="text-align: left;"><strong>避免不必要的属性查询</strong></p><p style="text-align: left;">使用变量和数组要比访问对象上的属性更有效率,因为对象必须在原型链中对拥有该名称的属性进行搜索。</p><pre class="brush:php;toolbar:false">// 使用数组
var values = [5, 10];
var sum = values[0] + values[1];
alert(sum);
// 使用对象
var values = { first: 5, second: 10};
var sum = values.first + values.second;
alert(sum);

上面代码中,使用对象属性来计算。一次两次的属性查找不会造成性能问题,但若需要多次查找,如在循环中,就会影响性能。

在获取单个值的多重属性查找时,如:

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

应该减少不必要的属性查找,将window.location.href缓存为变量。

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

函数节流

假设有一个搜索框,给搜索框绑定onkeyup事件,这样每次鼠标抬起都会发送请求。而使用节流函数,能保证用户在输入时的指定时间内的连续多次操作只触发一次请求。

<input>
// 绑定事件
document.getElementById('input').addEventListener('keyup', function() {
  throttle(search);
}, false);
// 逻辑函数
function search() {
  console.log('search...');
}
// 节流函数
function throttle(method, context) {
  clearTimeout(method.tId);
  method.tId = setTimeout(function() {
    method.call(context);
  }, 300);
}

节流函数的应用场景不局限搜索框,比如页面的滚动onscroll,拉伸窗口onresize等都应该使用节流函数提升性能。

最小化语句数

语句数量的多少也是影响操作执行速度的因素。

将多个变量声明合并为一个变量声明

// 使用多个var声明
var count = 5;
var color = "blue";
var values = [1,2,3];
var now = new Date();
// 改进后
var count = 5,
  color = "blue",
  values = [1,2,3],
  now = new Date();

改进的版本是只使用一个var声明,由逗号隔开。当变量很多时,只使用一个var声明要比单个var分别声明快很多。

使用数组和对象字面量

使用数组和对象字面量的方式代替逐条语句赋值的方式。

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

字符串优化

字符串拼接

早期浏览器未对加号拼接字符串方式优化。由于字符串是不可变的,就意味着要使用中间字符串来存储结果,因此频繁的创建和销毁字符串是导致它效率低下的原因。

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

把字符串添加到数组中,再调用数组的join方法转成字符串,就避免了使用加法运算符。

var arr = [],
  i = 0;
arr[i++] = "Hello";
arr[i++] = " ";
arr[i++] = "World!";
var text = arr.join('');

现在的浏览器都对字符串加号拼接做了优化,所以在大多数情况下,加法运算符还是首选。

减少回流和重绘

在浏览器渲染过程中,涉及到回流和重绘,这是一个损耗性能的过程,应注意在脚本操作时减少会触发回流和重绘的动作。

  1. 回流:元素的几何属性发生了变化,需要重新构建渲染树。渲染树发生变化的过程,就叫回流;

  2. 重绘:元素的几何尺寸没有变化,某个元素的CSS样式(背景色或颜色)发生了变化。

触发重排或重绘的操作有哪些?

  1. 调整窗口大小

  2. 修改字体

  3. 增加或者移除样式表

  4. 内容变化,比如用户在<input>框中输入文字

  5. 操作class属性

  6. 脚本操作DOM(增加、删除或修改DOM元素)

  7. 计算offsetWidth和offsetHeight属性

  8. 设置style属性的值

如何减少重排和重绘,提升网页性能?

1、脚本操作DOM元素

  1. 将DOM元素设置为display:none,设置过程中会触发一次回流,但之后可以随意改动,修改完后再显示;

  2. 将元素clone到内存中再进行操作,修改完后重新替换元素。

2、修改元素的样式

  1. 尽量批量修改,而不是逐条修改;

  2. 预先设定好id、class,再设置元素的className。

3、为元素添加动画时将元素CSS样式设为position:fixed或position:absolute,元素脱离文档流后不会引起回流。

4、在调整窗口大小、输入框输入、页面滚动等场景时使用节流函数(上面已提到过)。

HTTP

浏览器缓存

合理设置浏览器缓存是网页优化的重要手段之一。

Expires 和 Cache-Control

Expires出自HTTP1.0,Cache-Control出自HTTP1.1,同时设置两者时,Cache-Control 会覆盖 Expires。

  1. Expires指定的是实际过期日期而不是秒数。但Expires存在一些问题,如服务器时间不同步或不准确。所以最好使用剩余秒数而不是绝对时间来表达过期时间。

  2. Cache-Control可设置max-age值,单位秒,指定缓存过期时间。如:Cache-Control: max-age=3600。

ETag 和 Last-Modified

ETag 和 Last-Modified都由服务器返回在response headers中,其中ETag的优先级比Last-Modified高,也就是说服务器会优先判断ETag的值。

  1. ETag是附加到文档上的任意标签,可能是文档的序列号或版本号,或者是文档内容的校验等。当文档改变时ETag值也会随之改变。与ETag相关的是 If-None-Match,当浏览器发起请求时,会在If-None-Match字段携带ETag的值发给服务器;

  2. Last-Modified是文档在服务器端最后被修改的时间。与Last-Modified相关的是If-Modified-Since,当浏览器发起请求时,会在If-Modified-Since字段携带Last-Modified的值发送给服务器。

强缓存和协商缓存

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 the browser cache

  1. Add Expires and Cache-Control in the return response of the web server;

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

Why to reduce HTTP requests

Measures to reduce http requests account for a large part in performance optimization, such as: using css sprite images Replace multiple image requests, avoid empty src images, use inline images, use external link css and js, cache, etc.

The process from inputting the URL to completing the page loading includes:

  1. DNS resolution

  2. TCP connection

  3. HTTP request and response

  4. Browser rendering page

  5. Close the connection

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

Writing specifications and order in CSS practical projects

##css transition to make visible and invisible animation

The above is the detailed content of Basic performance optimization of front-end web pages. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Anchor Positioning Just Don't Care About Source OrderAnchor Positioning Just Don't Care About Source OrderApr 29, 2025 am 09:37 AM

The fact that anchor positioning eschews HTML source order is so CSS-y because it's another separation of concerns between content and presentation.

What does margin: 40px 100px 120px 80px signify?What does margin: 40px 100px 120px 80px signify?Apr 28, 2025 pm 05:31 PM

Article discusses CSS margin property, specifically "margin: 40px 100px 120px 80px", its application, and effects on webpage layout.

What are the different CSS border properties?What are the different CSS border properties?Apr 28, 2025 pm 05:30 PM

The article discusses CSS border properties, focusing on customization, best practices, and responsiveness. Main argument: border-radius is most effective for responsive designs.

What are CSS backgrounds, list the properties?What are CSS backgrounds, list the properties?Apr 28, 2025 pm 05:29 PM

The article discusses CSS background properties, their uses in enhancing website design, and common mistakes to avoid. Key focus is on responsive design using background-size.

What are CSS HSL Colors?What are CSS HSL Colors?Apr 28, 2025 pm 05:28 PM

Article discusses CSS HSL colors, their use in web design, and advantages over RGB. Main focus is on enhancing design and accessibility through intuitive color manipulation.

How can we add comments in CSS?How can we add comments in CSS?Apr 28, 2025 pm 05:27 PM

The article discusses the use of comments in CSS, detailing single-line and multi-line comment syntaxes. It argues that comments enhance code readability, maintainability, and collaboration, but may impact website performance if not managed properly.

What are CSS Selectors?What are CSS Selectors?Apr 28, 2025 pm 05:26 PM

The article discusses CSS Selectors, their types, and usage for styling HTML elements. It compares ID and class selectors and addresses performance issues with complex selectors.

Which type of CSS holds the highest priority?Which type of CSS holds the highest priority?Apr 28, 2025 pm 05:25 PM

The article discusses CSS priority, focusing on inline styles having the highest specificity. It explains specificity levels, overriding methods, and debugging tools for managing CSS conflicts.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment