search
HomeWeb Front-endHTML Tutorial网站前端性能优化

继前面几篇文章后再来说说老生常谈的话题,怎么样提升前端性能。文中很多取材自网络及《High Performance Web Sites》,并根据自己工作中所接触到的知识整理而成。

 http://hovertree.com/menu/webfront/

1. 减少HTTP请求

终端用户响应时间80%消耗在前端,而大部分时间都是在下载页面的资源:图片,脚本,flash等等,减少请求资源简化页面设计成为了性能提升的关键。尽量合并CSS、JS及图片文件,减少HTTP请求。

 

2. 使用内容分发机制

使用内容分发如CDN加速,使用户从离自己最近的服务器下载文件。但一般要求减少DNS查询次数,如同一个页面的请求资源尽量少的使用不同的主机名,可以减少网站并行下载的数量。但很多网站为了加速下载资源特意用了多个主机名,这样可以并行下载资源。在低版本的浏览器IE6,7中并行连接数为4个,高版本的IE8及以上以及现在较新版的chrome,firefox等浏览器都是6个。一般CSS,JS及图片资源均通过CDN加速,并且使用多个主机名来实现并行下载。

 

3. 设置header的过期时间,使内容可以缓存

这个规则可以从两个方面来看:

对于静态组件,实现“永不过期”的政策,通过设置一个较长时间的Expires头,例如图片,flash;

对于动态组件:使用适当的Cache-Control头来处理不同的请求,如CSS,JS等。

对于第一次访问网站的用户来说,图片资源等都是固定不变的,设置为永不过期的Expires头可以在客户端缓存,减少服务端的负载以及请求数量,而JS,CSS资源可以设置一个适当的过期时间。

 

但是实际上我们会遇到一个挑战:如果版本更新导致原来的CSS或JS有改动,如何确保终端用户是下载的最新的资源文件呢?

 

最最常用的一种方法,就是每次有改动时生成一个tag然后加在文件名称中,如果有修改文件名就会不一致,客户端就会强制获取最新的资源文件,amazon,google等都是这么处理的;当然还有一种办法就是在资源文件目录上打上tag,但是有一种弊端就是对于没有更改的文件客户端也会重新下载对应的资源,如果对于发布较为频繁的web项目,用户在首次访问时就比较耗性能。

 

4. 使用Gzip压缩内容

服务端可以把不只是html还有JS,CSS,XML等一切文本的响应都进行压缩,减小传输的大小

 

5. 样式放在页头

用户在打开一个页面时,浏览器会逐步的加载头部,导航栏及logo等,在加载过程中用户能看到页面的反馈,提升了用户体验。如果样式放在页脚,带来的问题是,包括在IE的很多浏览器上禁止逐步呈现,他们会阻止渲染,避免页面样式变化而引起重绘页面元素,用户就只能看到一个空白页。

 

6. JavaScript放在页脚

相对于CSS而言,JS提倡放在页脚加载避免阻碍其他资源的并行下载,对于内容性质的网站,将内容的HTML放在相对靠前的位置,而对于交互较多的网页,需要把特别重要的核心组件的JS剥离往前放,而不太重要的则在最后加载。更详细的关于Javascript的加载请查看上一篇文章:《从两个bug来看网页内容的装载》

 

7. 避免使用CSS表达式

CSS表达式计算会非常频繁,不仅仅是在渲染和resize时会执行,滚动页面甚至移动鼠标都会重新计算。

 

8. 外部引用JavaScript和CSS

如果通过引用外部JavaScript和CSS的形式,因为浏览器会缓存这些资源,下次访问时可以使得页面加载更快,而如果将它们写在HTML中每次访问页面时都会再次加载。

 

9. 减少DNS查询

这点与第2点有相似之处,需要做的就是在减少DNS查询次数与并发下载之间做好平衡。

 

10. 精简JavaScript和CSS

删除JS和CSS中的空白换行,注释等,使用混淆把JS中的长变量换成短变量,可以缩小他们的体积,减少请求数据所占用的网络带宽.

 

11. 避免重定向

除了在header中人为的重定向之外,网页重定向常在不经意间发生,被重定向的内容将不会使用浏览器的缓存。比如用户在访问www.xxx.com,服务器会通过301转向到www.xxx.com/,在后面加了一个“/”。如果服务器的配置不好,这也会给服务器带来额外的负担。通过配置apache的 alias或使用mod_rewrite模块等方法,可以避免不必要的重定向,而在ngingx中也可以直接配置rewrite规则。

 

12. 删除重复的脚本

在页面中重复的脚本会增加性能压力,美国20%的热门网站中都包含有重复的脚本,团队规模和脚本数量增加了出现重复脚本的几率。在IE中,包含重复的JS脚本会导致浏览器的缓存不被使用,同时增加不必要的请求(仅在IE,FF下不会出现重复的请求)和重复的脚本执行(在IE和FF下都会重复执行)。

 

13. 配置ETags

ETag是一种服务器和浏览器用于识别请求的浏览器已缓存的资源是否与服务端匹配的机制,比last-modified更灵活,能更加精确的知道文件是否被修改过,因为If-Modified-Since只能检查秒级的修改,而ETag是一个唯一的字符串,不会受到修改时间的限制。

 

顺便说说浏览器访问URL时的工作机制:

a. 第一次访问url时,用户从服务器段获取页面内容,并把相关的文件(images,css,js…)放在高速缓存中,也会把文件头中的expired time,last modified, ETags等相关信息也一同保留下来。

b. 用户重复访问url时,浏览器首先看高速缓存中是否有本站同名的文件,如果有,则检查文件的过期时间;如果尚未过期,则直接从缓存中读取文件,不再访问服务器。

c. 如果缓存中文件的过期时间不存在或已超出,则浏览器会访问服务器获取文件的头信息,检查last modifed或ETags等信息,如果发现本地缓存中的文件在上次访问后没被修改,则使用本地缓存中的文件;如果修改过,则从服务器上获取最新版本。

 

14. 使Ajax可缓存

Ajax如果使用POST请求的话,浏览器通常会假定用户是提交数据给服务端的,所以自然不会缓存,因为有数据提交就意味着服务端要所处理,而get形式的Ajax请求却可以缓存,如果对安全性没有特别高要求的可以使用get形式的Ajax请求。

 

15. 减少DOM节点,加速页面渲染

 

16. 避免404错误

 

17. 减少Cookie的大小,静态资源使用无cookie的域,客户端请求它们的时候,减少 Cookie 的反复传输对主域名的影响。Yahoo!使用yimg.com,YouTube使用ytimg.com.Amazon使用images-amazon.com

 

18. 避免频繁操作DOM节点,过多的操作还可能导致浏览器死机,据说之前twitter就因为在windows.scroll事件的操作中绑定了过多的dom操作而导致浏览器死机

 

19. 用LINK而不用@import方式导入样式

 

20. 给图片加上正确的宽高值,以减少页面重绘,同时可以防止图片缩放

 

21. 缩小favicon.ico并缓存,很多时候开发者都会忽略这个文件,但是每当有用户收藏网站/网页时,浏览器会自动请求这个文件,就算这个图标文件没有在你的网页中明显说明,浏览器也会请求,如果不添加就会出现404.

 

使用工具:

目前有一些工具可以用来做性能分析,并依据以上法则给出优化建议,值得我们使用,常见的工具如下:

Yslow: 雅虎针对前端网站优化提出了23条准则,同时开发了网页性能分析浏览器插件;

PageSpeed:是google推出的性能分析工具

dynaTrace: 是基于IE的分析工具

推荐:http://www.cnblogs.com/roucheng/p/texiao.html

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
HTML, CSS, and JavaScript: Examples and Practical ApplicationsHTML, CSS, and JavaScript: Examples and Practical ApplicationsMay 09, 2025 am 12:01 AM

The roles of HTML, CSS and JavaScript in web development are: 1. HTML is used to build web page structure; 2. CSS is used to beautify the appearance of web pages; 3. JavaScript is used to achieve dynamic interaction. Through tags, styles and scripts, these three together build the core functions of modern web pages.

How do you set the lang attribute on the  tag? Why is this important?How do you set the lang attribute on the tag? Why is this important?May 08, 2025 am 12:03 AM

Setting the lang attributes of a tag is a key step in optimizing web accessibility and SEO. 1) Set the lang attribute in the tag, such as. 2) In multilingual content, set lang attributes for different language parts, such as. 3) Use language codes that comply with ISO639-1 standards, such as "en", "fr", "zh", etc. Correctly setting the lang attribute can improve the accessibility of web pages and search engine rankings.

What is the purpose of HTML attributes?What is the purpose of HTML attributes?May 07, 2025 am 12:01 AM

HTMLattributesareessentialforenhancingwebelements'functionalityandappearance.Theyaddinformationtodefinebehavior,appearance,andinteraction,makingwebsitesinteractive,responsive,andvisuallyappealing.Attributeslikesrc,href,class,type,anddisabledtransform

How do you create a list in HTML?How do you create a list in HTML?May 06, 2025 am 12:01 AM

TocreatealistinHTML,useforunorderedlistsandfororderedlists:1)Forunorderedlists,wrapitemsinanduseforeachitem,renderingasabulletedlist.2)Fororderedlists,useandfornumberedlists,customizablewiththetypeattributefordifferentnumberingstyles.

HTML in Action: Examples of Website StructureHTML in Action: Examples of Website StructureMay 05, 2025 am 12:03 AM

HTML is used to build websites with clear structure. 1) Use tags such as, and define the website structure. 2) Examples show the structure of blogs and e-commerce websites. 3) Avoid common mistakes such as incorrect label nesting. 4) Optimize performance by reducing HTTP requests and using semantic tags.

How do you insert an image into an HTML page?How do you insert an image into an HTML page?May 04, 2025 am 12:02 AM

ToinsertanimageintoanHTMLpage,usethetagwithsrcandaltattributes.1)UsealttextforaccessibilityandSEO.2)Implementsrcsetforresponsiveimages.3)Applylazyloadingwithloading="lazy"tooptimizeperformance.4)OptimizeimagesusingtoolslikeImageOptimtoreduc

HTML's Purpose: Enabling Web Browsers to Display ContentHTML's Purpose: Enabling Web Browsers to Display ContentMay 03, 2025 am 12:03 AM

The core purpose of HTML is to enable the browser to understand and display web content. 1. HTML defines the web page structure and content through tags, such as, to, etc. 2. HTML5 enhances multimedia support and introduces and tags. 3.HTML provides form elements to support user interaction. 4. Optimizing HTML code can improve web page performance, such as reducing HTTP requests and compressing HTML.

Why are HTML tags important for web development?Why are HTML tags important for web development?May 02, 2025 am 12:03 AM

HTMLtagsareessentialforwebdevelopmentastheystructureandenhancewebpages.1)Theydefinelayout,semantics,andinteractivity.2)SemantictagsimproveaccessibilityandSEO.3)Properuseoftagscanoptimizeperformanceandensurecross-browsercompatibility.

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

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

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.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software