Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the ways to improve the loading speed of web pages

2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces "what are the ways to improve the loading speed of web pages". In the daily operation, I believe that many people have doubts about what methods to improve the loading speed of web pages. The editor consulted all kinds of materials and sorted out the simple and easy-to-use operation methods. I hope it will be helpful to answer the questions of "what methods to improve the loading speed of web pages". Next, please follow the editor to study!

precondition

Ideally, you should have Mozilla Firefox installed. You should also have a general understanding of Web development. The topics covered in this article are not complex, but if you understand topics such as Hypertext markup language (Hypertext Markup Language,HTML), cascading style sheets (Cascading Style Sheet,CSS), and the ™programming language, you will be more comfortable with this article. You don't need to use the integrated development environment (IDE), just use your favorite editor.

You must have JavaScript enabled in your browser. In addition, to learn about Firebug and YSlow, you need to install a Firefox Web browser.

Suppose you don't have broadband.

Many people access Internet through some form of broadband connection, which may be DSL, network cable, optical fiber, or other methods. However, users who cannot use this type of technology have to use dial-up connections. You must have forgotten what dial-up feels like, but you can try to think back to what it was like when a web page was loaded line by line.

Fortunately, these poor people have been able to get some help now. You can improve their experience by shortening the time it takes to load the page. However, dial-up connections are not the only reason for slowing down load and response times. Many Web designers mistakenly believe that the advent of high-speed Internet connections will make website performance optimization unnecessary. This view is wrong. For example, many tasks that were performed using desktop software in the past can now be performed online. It is very difficult to get a fast response experience like desktop software in Web applications, so performance optimization is very important. Fortunately, some tools and best practices can be used to reduce response and load times and provide a smoother experience.

Basic tools

For all optimization-related tasks, you must use tools to diagnose bottlenecks and identify problems. The two most widely used tools in Web development today are Firebug and YSlow, both open source and free Firefox plug-ins.

Firebug

Firebug (see Resources) is one of the most popular Firefox extensions, an application that makes life easier for Web developers. It contains many very useful features, such as:

JavaScript debugging

JavaScript Command Line

Monitor JavaScript performance and trace XmlHttpRequests

Log in to the Firebug console

Tracking

Check HTML elements and dynamically edit HTML code

Dynamic editing of CSS documents

YSlow

YSlow (see Resources) analyzes the web page, and according to Yahoo! Draft high-performance website rules (see reference) to tell you why the page loads slowly. YSlow is a Firefox plug-in integrated with Firebug, so you need to install Firebug before you can install and use YSlow.

Install Firebug

The installation process for both Firefox extensions is very simple. To install Firebug, perform the following steps:

Open Firefox and go to the Firebug home page.

Install the latest version of Firebug.

If Firefox is configured to block pop-up windows, click Allow to allow the installation window to open. Otherwise, click Install Now.

Restart Firefox.

You can now access Firebug from the Tools menu. You can open Firebug in a new window or in an existing window (see figure 1).

Install YSlow

After installing Firebug, install YSlow next. To do this, perform the following steps:

1. Open Firefox and go to the YSlow home page.

two。 Install the plug-in and restart Firefox. Note: unlike many other Firefox extensions, YSlow does not start automatically. It must be activated first.

3. To activate YSlow, right-click its icon in the status bar, and then click Autorun.

Figure 2 shows the results of the YSlow performance analysis.

Figure 2. YSlow performance analysis of Firefox start page

Common sense: keep in mind the design rules

Surprisingly, simple design rules are often ignored, resulting in unoptimized, slow-downloading web pages. Keep in mind the following rules, the page will load faster.

Use a good structure

Extensible HTML (XHTML) has many advantages, but its disadvantages are also obvious. XHTML may make your page more standard, but it uses a lot of tags (mandatory and tags), which means browsers have to download more code. So, there are two sides to everything, so try to use less XHTML code in your web page to reduce the page size.

If you do have to use XHTML, try to optimize it as much as possible. For example, delete spaces and adopt strict XHTML coding practices to improve download and parsing speed. To strictly enforce the XHTML Strict rules, add the following doctype statement to the document:

The code is as follows:

XHTML 1.0 Strict is equivalent to Strict HTML 4.01, and contains attributes and elements that do not appear in the objections to the HTML 4.01 specification. Remember, there are two tags that can be used in XHTML Transitional, but not in XHTML Strict, for example:

Do not overload the layout

Before blogs (and new sites) became popular, it was considered a bad practice to scroll the page horizontally or even vertically. The smaller the page, the more difficult (but not impossible) it is to fill the screen intact. Now, for blogs and content-driven sites, you can see hundreds of Kb-sized long pages from time to time. Yes, you need to fill more space, but that doesn't mean you have to fill it with a large background image, a large number of tables, or a lot of content. Adhere to the principle of simplicity: less is more. The page is full of various types of images, videos, advertisements, etc., which greatly violates the principle of practicality, so please think twice when adding content to the page.

Do not use images to represent text

We rarely control how fonts are displayed in different browsers, and unlike fonts, images are always displayed exactly the way they are designed. But this cannot be used as an excuse to use images to represent text.

The most common example of using images to represent text is in the navigation bar. Beautiful buttons are more attractive, but they load slowly. In addition, images still cannot be indexed directly by search engines, so using images for navigation is not conducive to search engine optimization (search engine optimization,SEO). When you can use a lot of CSS techniques to create beautiful buttons without images, never use images to represent text.

A specific type of navigation that applies to the CSS style is tabbed navigation, as shown in figure 3.

Figure 3. Tabbed navigation

In addition to being small, this way of implementing navigation is also more Web-compliant.

The code in listings 1 and 2 implements tab-based navigation in pure CSS/XHTML.

Listing 1. CSS documents based on Tab Navigation

The code is as follows:

# nav {

Float:left

Width:100%

Background:#E7E5E2

Font-size:95%

Line-height:normal

Border-bottom:1px solid # 54545C

}

# nav ul {

Margin:0

Padding:10px 10px 0 50px

List-style:none

}

# nav li {

Display:inline

Margin:0

Padding:0

}

# nav a {

Float:left

Background:url ("tableftK.gif") no-repeat left top

Margin:0

Padding:0 0 0 4px

Text-decoration:none

}

# nav a span {

Float:left

Display:block

Background:url ("tabrightK.gif") no-repeat right top

Padding:5px 15px 4px 6px

Color:#FFF

}

/ * Commented Backslash Hack hides rule from IE5-Mac\ * /

# nav a span {float:none;}

/ * End IE5-Mac hack * /

# nav a:hover span {

Color:#FFF

Background-position:100%-42px

}

# nav a:hover {

Background-position:0%-42px

}

# nav a:hover span {

Background-position:100%-42px

}

Listing 2. HTML code based on tab navigation

The code is as follows:

Link 1

Link 2

Link 3

Longer Link Text

Link 5

Check cookie usage

Cookie may be small files, but browsers still need to download them. Larger cookie takes longer to download, which in turn increases the time it takes for browsers to load web pages. Because of this, it is important to minimize the impact on browser response time by minimizing cookie as much as possible.

In addition, setting an earlier expire date or not setting an expire date at all reduces response time. To set the expire date for cookie in the PHP language, use the following code:

The code is as follows:

This code sets the cookie userid and sets the expire date to 30 days after the current date.

Don't include unnecessary JavaScript code, externalize it as much as possible

Like cookie, it takes time to download JavaScript files, which inevitably slows down the loading speed of the entire page. Therefore, use JavaScript wisely (only when really necessary) and optimize the size and speed of the script.

Another way to reduce JavaScript download time is to use external files instead of including inline scripts. This approach also works for CSS, because browsers cache externalized text, and CSS or JavaScript encoded inline (in the HTML page itself) is loaded with HTML each time. To externalize CSS and JavaScript code by referencing them in HTML, you can use code in the following form:

The code is as follows:

Avoid using forms as much as possible

Tables are used as the main building blocks of web pages, but as page layout elements, using tables is now considered a bad practice. Sometimes you have to use tables (and they are considered an excellent practice for displaying tabular data). If so, explicitly specify the width and height of table cells, rows, and columns, otherwise the browser must perform a number of actions to calculate how to display them, which slows down the page load:

The code is as follows:

...

Delete any unnecessary elements

This may be the most obvious of all techniques, but it is also one of the easiest to forget. I once mentioned that "less is more": this is not only to really attract a wider range of users, but also means less stuff to download and process. If you really need to put a lot of content on a page, consider dividing the page into 2, 3, or more separate pages.

Some techniques for optimizing web pages

There are many ways to optimize your web pages, including compressing JavaScript files, using Hypertext transfer Protocol (Hypertext Transfer Protocol,HTTP) compression, and setting image sizes.

Compress and shrink JavaScript files

JavaScript files can be very large, which means that in some cases, they may take longer to download than all other components combined. One way to solve this problem is to compress the JavaScript file. You can use GNU zip (gzip) to do this because many browsers support this compression algorithm.

Another alternative is to shrink the file. This method removes all unnecessary characters in the code, such as tabs (tab), new lines, and spaces. It removes comments and whitespace from the code to further reduce the file size. Both external and internal stylesheets can be reduced. The two most popular zoom-out tools are JSMin and YUI Compressor (see Resources).

Use HTTP compression and always use lowercase div and class names

You can use HTTP compression to reduce traffic between the server and the browser. You can configure HTTP compression (.htaccess file) in Apache, or you can include it in the page (for PHP, you can use a HTTP_ACCEPT_ENCODING option). Note, however: not all browsers support compression. Even for browsers that support compression, compression and decompression can increase the load on the processor. To enable blanket compression (that is, compress all text and HTML) in Apache, use the following command:

The code is as follows:

AddOutputFilterByType DEFLATE text/html text/plain text/xml

In addition, consider what you want to compress. Images, music, and videos are already compressed at the time of creation, so you can limit compressed objects to HTML, CSS, and JavaScript files.

Another technique for reducing compression effort is to use lowercase elements and class names. Because of case sensitivity and the use of lossless compression, they are compressed into two different tags. In the following example, the Important class is different from the important class for the compressed program, which means that for the compressed program, they represent different objects and are therefore compressed into two different pieces of text.

The code is as follows:

Read this!

This will cost you some valuable load time

Paying attention to the details doesn't seem to matter. But when you optimize the file, all the subtle details should be taken into account.

Set the image size

Like table cells, rows, and columns, when you do not explicitly set the image size, the browser needs to perform calculations to display the image, which slows down processing. In addition, in some cases, the calculation of the image size may be incorrect, so the image will be deformed.

Using CSS Image Mapping for Decoration

Using image mapping instead of multiple images is another way to reduce load time, because downloading separate parts of the image at the same time can speed up the download of the entire page. Alternatively, you can use a tool called CSS sprites (see Resources). CSS sprites helps reduce the number of HTTP requests. An image can contain all the image elements needed to decorate or decorate a page. You use CSS to select (by invoking certain locations and dimensions) for the mapping of specific elements.

Delay script loading as much as possible

As I mentioned earlier, removing completely unnecessary JavaScript code can speed up loading and processing. But what if the code is already very compact and must include JavaScript code in the page?

In this case, a potential way to increase the page download speed is to place the script at the bottom of the page to make the page load faster. Typically, browsers can only download no more than two parallel objects (from the same domain), and if one object is a piece of JavaScript code, the download of other page components will be paused until the script is downloaded. If you put the JavaScript code at the bottom of the page, (in most cases) it will be downloaded last, when all other components have been downloaded.

Use the Firebug extension to track slow-loading files, and I bet your JavaScript file is the slowest to download. Compressing the JavaScript file will help, but that alone may not be enough. You can delay the loading of JavaScript using the following code snippet:

The code is as follows:

Var delay = 5

SetTimeout ("heavy ();", delay * 1000)

This code delays the call to the heavy () method by five seconds. You can use this code in conjunction with the following technique to delay the loading of the entire JavaScript file.

Load JavaScript files on demand

To load JavaScript on demand, use the import () function, as shown in listing 3.

Listing 3. Import () function

The code is as follows:

Function $import (src) {

Var scriptElem = document.createElement ('script')

ScriptElem.setAttribute ('src',src)

ScriptElem.setAttribute ('type','text/javascript')

Document.getElementsByTagName ('head') [0] .appendChild (scriptElem)

}

/ / import with a random query parameter to avoid caching

Function $importNoCache (src) {

Var ms = new Date (). GetTime (). ToString ()

Var seed = "?" + ms

$import (src + seed)

}

Verify function loading

You can also verify that a function is loaded, and if not, load the JavaScript file. To do this, use the code in listing 4.

Listing 4. Verify that the function is loaded

The code is as follows:

If (myfunction) {

/ / The function has been loaded

}

Else {/ / Function has not been loaded yet, so load the javascript.

$import ('http://www.yourfastsite.com/myfile.js');

}

Note: you can use the defer attribute, but not all browsers (including Firefox) support it.

Optimize CSS files

If properly optimized and maintained, the CSS file is not necessarily very large. For example, CSS files with many separate classes can affect download speed. Like JavaScript files, you need to optimize the CSS file to contain everything you need while maintaining a reasonable size. In addition, use external files instead of inline definitions to adapt to the browser's caching mechanism.

Use content to distribute the network

The content Distribution Network (Content-distribution network,CDN) is another good way to shorten download time. When you place still images on many servers on Internet, users can download them from the server closest to them. In addition, most CDN runs on fast servers, so no matter how fast the server loads, it responds faster than small overloaded servers.

Use multiple domains for assets to increase connectivity

Another advantage of CDN is that they are separate domains. Because your browser limits the number of concurrent connections to a single domain, it is easy to fill all threads whenever a page is loaded. As a result, connections to other assets are delayed. However, your browser can open new threads or connections to other domains so that any asset loaded from another domain can be loaded at the same time as all other assets.

Use Google Gears when appropriate

Using Google Gears (see Resources) is another good way to avoid users downloading the same content over and over again. Gears allows users to access Web applications offline, but it also allows page elements to be persisted to the user's computer. Therefore, content that is loaded frequently but not updated can be stored in a Gears database, which is a SQLite3 relational database management system. All next requests for the same content can be loaded directly from the database (not the server).

After installing Gears, get the gears_init.js file so that you can easily access the Gears factory and application programming interface (API), save it as gears_init.js, and reference it in your code in the following ways:

The code is as follows:

To determine if Gears is installed, use the code in listing 5.

Listing 5. Determine if Gears is installed

The code is as follows:

If (! window.google | |! google.gears) {

Location.href = "http://gears.google.com/?action=install&message="

+ & return=

}

If Gears is not installed, the code will provide you with the URL to download Gears.

After all the elements have been validated and Gears has been installed, you can test the extremely useful database functionality of Gears, using the JavaScript code in listing 6.

Listing 6. Test database function

The code is as follows:

Var db = google.gears.factory.create ('beta.db')

Db.open ('database-test')

Db.execute ('create table if not exists Test' +

'(Phrase text, Timestamp int)')

Db.execute ('insert into Test values (?,)', ['Monkeycake, new Date (). GetTime ()])

Var rs = db.execute ('select * from Test order by Timestamp desc')

While (rs.isValidRow ()) {

Alert (rs.field (0) +'@'+ rs.field (1))

Rs.next ()

}

Rs.close ()

This code creates a local database db on your computer or server. If the table Test does not exist, create one and insert the test data (Monkey! And time). The code fetches the data from the database and renders it as a warning in the browser.

Imagine what might happen!

Use images in PNG format

Both Graphic Interchange Format (GIF) and Joint Photographic Experts Group (JPEG) image formats are out of date: Portable Network Graphic (PNG) is the popular format of the future. Of course, you can say that GIF and JPEG are dead, or that PNG doesn't have any flaws, but everything has its own advantages and disadvantages, and PNG provides excellent quality with the best file size. Therefore, if you make a choice, you should use PNG images whenever possible.

Keep Ajax calls short and accurate

When technologies collectively known as Asynchronous JavaScript + XML (Ajax) emerged two years ago, they provided a revolutionary way to handle page requests and responses. However, dial-up users may never have a chance to experience their real advantages, because in many cases, Ajax requires a lot of communication between the browser and the server. Therefore, if you can keep Ajax calls short and accurate, you can prevent users from spending endless time waiting for elements to refresh or respond.

Make a large Ajax call and process client data locally

If short Ajax calls cannot be made, or if they do not provide the desired results, consider an alternative: make a large Ajax call to get everything you need, and then let the client process the data locally. In this way, the client only needs to wait once (to get the incoming data), but after that (when there is no need for communication between the browser and the server), the processing speed will be faster. Of course, there are a large number of Ajax optimization techniques that cannot be listed in this tutorial. If you want to learn more about Ajax, check out Resources.

Test the code in a sandbox

There is also a common technique that is often forgotten. Although sober Web developers usually test an application before starting it, sometimes testing makes them pay less attention to maintenance tasks, or new features are added too quickly and not fully considered or tested. As a result, the remaining scripts slow down the application.

If you add a new feature, you can first test it in a sandbox (completely detached from the rest of the application) to see how it behaves as a single function. In this way, you can repeatedly check and analyze performance and response time, regardless of the rest of the Web application. Then, when the new feature behaves as expected, you can introduce it into the rest of the application and run other tests to ensure that the feature itself behaves as expected.

Analyze the site code

In many scenarios, self-reflection is a good suggestion. Fortunately, during the development process, we can use tools to help reflect and practice as objectively as possible. The value of a tool such as JSLint (see Resources) is immeasurable, although its site claims that it "can be frustrating for you" because it provides you with all the potential code flaws that not only make debugging more difficult, but can also lead to longer response times.

Use JSLint to check JavaScript code for errors or poor coding practices

You don't need to pursue perfect JavaScript code like a perfectionist. However, many developers do not take code analysis seriously and usually skip this step in the development process. Unfortunately, errors and poor coding practices are not only unprofessional, but can also slow down applications. When browsers are busy dealing with errors and poor coding practices, loading not only takes more time, but also leads to errors that are difficult to debug.

Therefore, if you want to get good code, consider using code analysis tools. There are many different tools available, but the most suitable tool for the JavaScript language is JavaScript Lint, also known as JSLint (see Resources). You can also use Firebug, but JSLint is more formal and is included in YSlow.

Check for orphaned files and missing images

It is wise to check for orphaned files and missing images. Most Web developers check for incorrect file references, but they still need to be explained here. Missing files can easily cause problems because they can lead to error messages such as "The image/page cannot be displayed". But in terms of web page speed optimization, they have a bigger flaw: when browsers look for missing or isolated files, they consume resources, which inevitably leads to slower page processing. Therefore, check for orphaned or missing files, including misspelled file names.

YSlow extension

YSlow Firebug extension makes subjective web analysis obsolete day by day. YSlow uses Yahoo! Draft authoritative rules for high-performance websites, analyze web pages and tell you why they are slow.

Use YSlow to analyze web pages

YSlow is a relatively small but very useful Firefox extension. When you start YSlow, the extension opens in the lower half of the browser, as shown in figure 4.

Figure 4. YSlow extension in Firefox

Figure 4 shows the Performance view, where you can see how YSlow evaluates the performance of your web page, as well as the problems detected by the extension. Clicking a link in the list opens a page that explains the error. If there are page components that can be improved, YSlow gives suggestions for improvement.

In the Inspect view, as shown in figure 5, you can analyze the elements one by one to parse the page. One of the most useful features of the Inspect view is that it automatically refreshes when you move the mouse pointer over the page, so you don't have to scroll through the contents of the code to find the lines you need to check.

Figure 5. YSlow Inspect view in Firefox

As you can guess from the name of the Stats view, it (shown in figure 6) displays statistics related to the current page. This data includes empty and primary caches and cookie.

Figure 6. YSlow Stats view in Firefox

The Components view (shown in figure 7) lists the components on the current page. The data displayed for each component includes the file type and path, the page expiration time, and the HTTP response header. Click a component to open it for viewing. Click a column header to sort the table in ascending or descending order.

Figure 7. YSlow Components view

YSlow is a small, useful extension that can help you a lot in terms of improving page loading speed. If you haven't used it before, you should use it now.

At this point, the study on "what are the ways to improve the loading speed of web pages" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report