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!

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

Dreamweaver Mac version
Visual web development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

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