search
HomeWeb Front-endJS TutorialHow to optimize web page performance

How to optimize web page performance

Sep 22, 2017 am 10:17 AM
optimizationperformanceWeb page

The front-end is huge, including HTML, CSS, Javascript, Image, Flash and other various resources. Front-end optimization is complex, and there are different methods for all aspects of resources. So, what is the purpose of front-end optimization?

 1. From a user perspective, optimization can make pages load faster, respond more promptly to user operations, and provide users with a more friendly experience.
 2. From the perspective of service providers, optimization can reduce the number of page requests or reduce the bandwidth occupied by requests, which can save considerable resources.
In short, proper optimization can not only improve the user experience of the site but also save considerable resource utilization.
There are many ways to optimize the front-end, which can be roughly divided into two categories according to the granularity. The first category is page-level optimization, such as the number of HTTP requests, non-blocking loading of scripts, position optimization of inline scripts, etc.; the second category It is code-level optimization, such as DOM operation optimization in Javascript, CSS selector optimization, image optimization, HTML structure optimization, etc. In addition, with the purpose of improving the input-output ratio, the various optimization strategies mentioned later are roughly arranged in order from large to small input-output ratio.
1. Page-level optimization
1. Reduce the number of HTTP requests
This strategy is basically known to all front-end people, and it is also the most important and effective. It is said that HTTP requests should be reduced, but what will happen if there are too many requests? First of all, each request has a cost, including both time cost and resource cost. A complete request requires a "long" and complicated process of DNS addressing, establishing a connection with the server, sending data, waiting for the server to respond, and receiving data. The time cost is that the user needs to wait for the process to end to see or "feel" the resource. Since each request on the resource needs to carry data, each request requires bandwidth. In addition, since there is an upper limit on the number of concurrent requests that the browser can make (see here for details), when the number of requests increases, the browser needs to make requests in batches, which will increase the user's waiting time and cause problems to the user's site. The impression of slow speed is that even if all the resources on the first screen that the user can see have been requested, the browser's progress bar will always exist.
The main ways to reduce the number of HTTP requests include:
(1). Simplify the page from the design and implementation level
If your page is as simple as Baidu’s homepage, then the following rules are basically unnecessary. It’s most straightforward to keep the page simple and reduce resource usage. If not, and your page needs a gorgeous skin, then continue reading below.
 (2). Properly set up HTTP cache
The power of cache is powerful, and proper cache settings can greatly reduce HTTP requests. Taking Youa's homepage as an example, when the browser does not cache it, a total of 78 requests will be issued, with a total of more than 600K data (as shown in Figure 1.1). However, when the second visit is after the browser has cached it, only 10 requests will be made. requests, with a total of more than 20K data (Figure 1.2). (It should be noted here that if you directly refresh the page with F5, the effect will be different. In this case, the number of requests is still the same, but the request server for the cached resource is a 304 response. Only the Header has no Body, which can save bandwidth)
What is a reasonable setting? The principle is very simple. The more you can cache, the better, and the longer you can cache, the better. For example, image resources that rarely change can directly set a long expiration header through Expires in the HTTP Header; resources that change infrequently but may change can use Last-Modifed for request verification. Keep resources in the cache as long as possible. The specific settings and principles of HTTP caching will not be described in detail here. Those who are interested can refer to the following articles:
Description of caching strategies in HTTP1.1 protocol
Fiddler HTTP Performance Introduction to caching in
 (3). Resource merging and compression
If possible, try to merge external scripts and styles into one. In addition, CSS, Javascript, and Image can all be compressed using corresponding tools. After compression, a lot of space can often be saved.
 (4). CSS Sprites
Another good way to merge CSS images and reduce the number of requests.
 (5). Inline Images
 Use data: URL scheme is a good way to embed images into pages or CSS if resource management issues are not considered. If it is embedded in the page, the size of the page will be increased, and the browser cache cannot be used. Images used in CSS are more ideal.
 (6). Lazy Load Images (I still don’t understand the content of this section)
This strategy may not actually reduce the number of HTTP requests, but it can reduce the number of HTTP requests under certain conditions or when the page is just loaded. For pictures, you can load only the first screen when the page is just loaded, and only load subsequent pictures when the user continues to scroll back. In this way, if the user is only interested in the content of the first screen, the remaining image requests will be saved. Yes Home Page The previous approach was to cache the image addresses after the first screen in the Textarea tag when loading, and then load them "lazily" when the user scrolls down.

 2. Put the external script at the bottom (load the script content after the page information content is loaded)
As mentioned earlier, the browser can request concurrently, which makes it faster Loading resources, however, external link scripts will block other resources when loading. For example, before the script is loaded, the images, styles and other scripts behind it are blocked and will not start loading until the script is loaded. If the script is placed in a relatively high position, it will affect the loading speed of the entire page and thus affect the user experience. There are many ways to solve this problem, in Here is a more detailed introduction (Here is the translation and More detailed examples ), and the simplest and most reliable method is to move the script as far back as possible to reduce the impact on concurrent downloads.
 3. Asynchronous execution of inline scripts (In fact, the principle is the same as above, ensuring that the script is loaded after the page content.)
 The impact of inline scripts on performance is even worse than that of external scripts. Home page, like external scripts, inline scripts will also block concurrent requests when executed. In addition, since the browser is single-threaded in page processing, when the inline script is executed before the page is rendered, the page rendering work will be postponed. In short, when the inline script is executed, the page is blank. In view of the above two reasons, it is recommended to execute inline scripts that take a long time to execute asynchronously. There are many asynchronous methods, such as using the defer attribute of the script element (there are compatibility issues and other problems, such as document.write cannot be used), Use setTimeout , in addition, introduced in HTML5 The mechanism of Web Workers can exactly solve such problems.

4. Lazy Load Javascript (Only loaded when loading is required, information content is not loaded under normal circumstances.)
With the popularity of Javascript frameworks, more and more sites are using it. frame. However, a framework often includes many functional implementations. These functions are not required by every page. If you download unnecessary scripts, it is a waste of resources - it wastes both bandwidth and execution time. . There are currently two approaches. One is to customize a dedicated mini version of the framework for pages with particularly high traffic, and the other is Lazy Load. YUI uses the second method. In the implementation of YUI, only the core module is loaded initially, and other modules can wait until they are needed.

 5. Put CSS in HEAD
If you put CSS in other places such as BODY, the browser may start rendering the page before downloading and parsing the CSS, which results in The page jumps from the CSS-less state to the CSS state, which results in a poor user experience. In addition, some browsers will only start rendering the page after the CSS is downloaded. If the CSS is placed at a lower position, it will cause the browser to delay the rendering time.
 6. Asynchronous request Callback (that is, extracting some behavioral styles and slowly loading the information content)
 There may be such a requirement in some pages that requires the use of script tags to request data asynchronously. Similar:
Javascript:
/*Callback function*/
function myCallback(info){
//do something here
}
HTML:

Content returned by cb:
myCallback('Hello world!');
Writing <script> directly on the page in the above way also has an impact on the performance of the page, that is, increasing the number of pages The burden of first loading delays the triggering of DOMLoaded and window.onload events. If timeliness allows, you can consider loading when the DOMLoaded event is triggered, or use the setTimeout method to flexibly control the loading timing. <br/> 7. Reduce unnecessary HTTP jumps<br/>For HTTP links accessed in directory form, many people will ignore whether the link has a '/' at the end. If your server treats this differently, then you should also It should be noted that there may be hidden 301 jumps and redundant requests. See the figure below for details. The first link is accessed without a '/' ending, so the server has a jump. <br/> 8. Avoid repeated resource requests<br/> This situation is mainly due to negligence or the page is spliced ​​from multiple modules, and then when the same resource is requested in each module, it will lead to repeated resource requests</script>

 2. Code-level optimization
 1. Javascript
 (1). DOM
 DOM operations should be the most performance-consuming operations in scripts, such as adding, modifying, deleting DOM elements or modifying DOM collections to operate on. If the script contains a large number of DOM operations, you need to pay attention to the following points:
a. HTML Collection (HTML collector, returns an array content information)
In the script document.images, document.forms, getElementsByTagName() returns a collection of HTMLCollection type. In daily use, it is mostly used as an array, because it has a length attribute, and each element can also be accessed using an index. However, the access performance is much worse than that of an array. The reason is that this collection is not a static result. It only represents a specific query. Each time the collection is accessed, the query will be re-executed to update the query results. The so-called "accessing a collection" includes reading the length property of the collection and accessing the elements in the collection.
Therefore, when you need to traverse the HTML Collection, try to convert it into an array before accessing it to improve performance. Even if it is not converted into an array, please access it as little as possible. For example, when traversing, you can save the length property and members to local variables and then use the local variables.
b. Reflow & Repaint
In addition to the above point, DOM operations also need to consider the browser's Reflow and Repaint, because these require resource consumption. For details, you can refer to the following article:
How to reduce Browser repaint and reflow?
Understanding Internet Explorer Rendering Behavior
Notes on HTML Reflow

 (2). Use with
with(obj){ p = 1}; with caution. The behavior of the code block actually modifies the code in the code block. Execution environment , placing obj at the front end of its scope chain. When accessing non-local variables in the with code block, the search starts from obj. If not, it searches upward according to the scope chain. Therefore, using with is equivalent to increasing the length of the scope chain. Each search for a scope chain takes time, and a scope chain that is too long will cause search performance to decrease.
Therefore, unless you are sure that you are only accessing the properties in obj in the with code, use with with caution. Instead, you can use local variables to cache the properties that need to be accessed.
 (3). Avoid using eval and Function
 Every time the eval or Function constructor acts on source code represented by a string, the script engine needs to convert the source code into executable code. This is a very resource-intensive operation - often more than 100 times slower than a simple function call.
The eval function is particularly inefficient. Since the content of the string passed to eval cannot be known in advance, eval interprets the code to be processed in its context. This means that the compiler cannot optimize the context, so the browser can only Code is interpreted at runtime. This has a big impact on performance.
 The Function constructor is slightly better than eval because using this code does not affect surrounding code; but it is still slow.
In addition, using eval and Function is not conducive to Javascript compression tools performing compression.
 (4). Reduce scope chain search (this aspect is designed to address some content-related issues)
The previous article talked about the scope chain search problem, which is an issue that requires special attention in loops. If you need to access a variable outside of this scope in a loop, please cache the variable with a local variable before traversing, and rewrite that variable after the traversal. This is especially important for global variables, because global variables are in scope. The top of the chain has the highest number of searches during access.
Inefficient writing:
// Global variable
var globalVar = 1;
function myCallback(info){
for( var i = 100000; i--;){
//Every time you access globalVar, you need to find the top of the scope chain. In this example, you need to access 100,000 times
globalVar += i;
}
}
More efficient writing:
//Global variable
var globalVar = 1;
function myCallback(info){
//Local variable cache global variable
var localVar = globalVar;
for( var i = 100000; i--;){
//Accessing local variables is the fastest
localVar += i;
}
//In this example, global variables only need to be accessed 2 times
In the function You only need to assign the value of the content in globalVar to localVar.
globalVar = localVar;
}
In addition, to reduce the scope chain search, you should also reduce the use of closures.
 (5). Data access
 Data access in Javascript includes direct quantities (strings, regular expressions), variables, object properties and arrays, among which access to direct quantities and local variables is the fastest. Access to object properties and arrays requires greater overhead. When the following situations occur, it is recommended to put data into local variables:
a. Access to any object property more than once
b. Access any array member more than once
In addition, you should Reduce deep search of objects and arrays as much as possible.
 (6). String splicing
Using the "+" sign to splice strings in Javascript is relatively inefficient, because each run will open up new memory and generate new string variables, and then The splicing result is assigned to a new variable. A more efficient approach is to use the join method of the array, that is, put the strings to be spliced ​​in the array and finally call its join method to get the result. However, since using arrays also has a certain overhead, you can consider using this method when there are many strings that need to be spliced.

For a more detailed introduction to Javascript optimization, please refer to:
Write Efficient Javascript (PPT)
Efficient JavaScript
2. CSS selectors
In most people’s minds, browsers parse CSS selectors from left to right, such as
#toc A { color: #444; }
Such a selector , if it is parsed from right to left, the efficiency will be very high, because the first ID selection basically limits the search range, but in fact the browser parses the selector from right to left. As with the selector above, the browser must traverse to find the ancestor nodes of each A tag, and the efficiency is not as high as previously thought. According to this behavioral characteristic of the browser, there are many things that need to be paid attention to when writing selectors. Someone has already listed them one by one. See here for details.

3. HTML
The optimization of HTML itself is attracting more and more attention nowadays. For details, please refer to this article Summary article .

 4. Image Compression
Image compression is a technical activity, but nowadays there are many tools in this area. Compression can often bring good results. The specific compression principles and methods are in "Even Faster Web Sites" Chapter 10 has a very detailed introduction, if you are interested, you can read it.
 Summary
This article summarizes the various methods of front-end optimization from the two granularities of page level and code level. These methods are basically what front-end developers can learn from and practice during the development process, except In addition, complete front-end optimization should also include many other ways, such as CDN, Gzip, multiple domain names, cookie-less servers, etc. Since the operability for developers is not strong, I will not describe it here. , for details, please refer to these "golden rules" of Yahoo and Google

The above is the detailed content of How to optimize web page performance. 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
From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

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.

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.

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.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment