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

How to make Web applications run quickly

2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article focuses on "how to make Web applications run quickly". Friends who are interested may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to make Web applications run quickly.

Problem: blank content

When developers work with CSS or JavaScript files, blank content is usually a good thing. White space includes characters used in indented files, spacing to enhance readability, and additional blank lines inserted to add a visual interval to different parts of the article. Blank content makes the file easy to read and maintain. Consider the CSS file in listing 2 with the appropriate amount of blank content (and comments) to help developers understand the intent of the CSS code.

At this point, it is not feasible to make the file smaller as a long-term solution to the problem, as the file is likely to be modified in the future. If you delete all the blank content and registration, the CSS and JavaScript code will be difficult to read.

The problem is that the increasing whitespace causes the file to grow. Each space between blank lines, indents, and parentheses takes at least one extra character, which is not actually required for proper parsing of CSS or JavaScript code. First of all, one or two blanks is no big deal, but when a small number is multiplied by a large multiple, it becomes a large number.

Consider such a file in which the extra whitespace totals 5KB. If your website has 1000 hits per day, saving 5KB per day can save about 146MB ((5K * 1000 * 30) / 1024 as a rough estimate) per month. In this regard, the number of clicks on the document is still a relatively conservative estimate, and the actual blank cost is likely to increase.

In addition, the user who downloads your file must wait for the file to download. Although many users may have cached CSS or JavaScrip files after their visits to your site, performance can have a negative impact on their visits. If you can reduce your CSS and JavaScript files, even 1 KB at a time, you can reduce the amount of data that browsers must load with thousands of bytes.

Head-to-page solution: compression

To solve the problem and benefit from small resources, an obvious solution is to remove additional elements, such as comments and whitespace, from your CSS and JavaScript files. However, since it is not feasible to remove comments and whitespace from your files during development, a better solution is to "grade" your site resources, optimize them, and then publish them.

Writing a custom script to remove whitespace characters sounds like a viable solution at first, but there are important whitespace in both CSS and JavaScript files. So any tool that deletes whitespace and compresses files must be smart enough to tell which whitespace is important in which languages.

Fortunately, such tools are already available in the community, and they have been tested for compression of resources such as CSS and JavaScrip files. One of these tools is YUI Compressor, an available tool from Yahoo! ®Developer Network (see Resources for a link).

YUI Compressor

YUI Compressor is a program written in Java with a Berkeley Software Distribution license. YUI Compressor can shrink (compress) your CSS and JavaScript code so that you can enjoy the benefits of small resources without having to write your own tools.

Download YUI Compressor, then extract the file and place it in an easily accessible location. The archive includes the complete source code and an Apache Ant script (build.xml) for building the YUI Compressor. However, if you do not want to build the file, you can find yuicompressor- {version} .jar in the build directory (see figure 1).

Figure 1. Archive file directory

The JAR file for YUI Compressor is included, and you can copy it to another project and execute it by entering the following command:

Java-jar yuicompressor-2.4.2.jar-- help

In addition to downloading this file, there is another way to use the XML file in listing 1 to add YUI Compressor to your Apache Maven pom.xml or Apache IVY file.

Listing 1. Add YUI Compressor to Maven or IVY

Com.yahoo.platform.yui yuicompressor 2.3.6

Pass the parameter-h to the yuicompressor.jar file to display the basic usage information of YUI Compressor.

Compressed CSS

Listing 2 is an example of a CSS optimized for developer maintenance, which contains comments and is formatted in white space.

Listing 2. CSS files optimized for maintenance

/ * The main body for the page. * / body {font-family: Tahoma,Geneva,sans-serif; background-color: # e2e2e2; margin: 00; padding: 00;} / * The header and header elements * / # header, # content, # footer {padding 0; margin 0; width: 100%; min-width: 600px;} # header a {text-decoration: none; border: none } # header {background: # fff url ('images/lb-h.jpg') repeat-x top; height: 115px;} # header img.logo {position: absolute; border: none; margin-top: 10px; margin-left: 50px; z-index: 1000;} / * Top banner... * / # banner {margin: 0; padding: 0; background-color: # fff; border-bottom: 1px solid # bebebe; height: 265px; text-align: center;} / * This is the main content * / # content {background: # fff url ('images/lb-g.jpg') repeat-x top; min-height: 450px; display: inline-block; clear: both } # footer {border-top: 3px solid # bebebe; clear: both; min-height: 100px; font-size: smaller;} # followicons {margin-left: 50px;}

To compress an CSS file, run the following command:

Java-jar yuicompressor-2.4.2.jar-o sample.min.css sample.css

After the file is compressed, the output looks like listing 3. The listing is formatted for easy reading, but the YUI Compressor output doesn't wrap: all you see is on one line.

Listing 3. Compressed CSS file

Body {font-family:Tahoma,Geneva,sans-serif;background-color:#e2e2e2;margin:0;padding:0;} # header,#content,#footer {padding 0 position margin 0 position widthlue 100% repeat-x top;height:115px; header img.logo 600 px; # header a {text-decoration:none;border:none;} # header {background:#fff url ('images/lb-h.jpg') widthWidth} # header img.logo {position:absolute;border:none;margin-top:10px; margin-left:50px Banner {margin:0;padding:0;background-color:#fff; border-bottom:1px solid # bebebe;height:265px;text-align:center;} # content {background:#fff url ('images/lb-g.jpg') repeat-x top;min-height:450px;display:inline-block;clear:both;} # footer {border-top:3px solid # bebebe;clear:both;min-height:100px;font-size:smaller;} # followicons {margin-left:50px;}

In addition to simply removing whitespace and comments, YUI Compressor performs a number of other optimizations on your CSS to make the file smaller. So what exactly did you do to the CSS code to make the file smaller?

◆ removes whitespace. Any unnecessary white space, such as indentation, blank lines, and spaces between elements and parentheses are deleted. If CSS whitespace is necessary for normal operation, it will be retained (see listing 4).

Listing 4. Delete excess whitespace

/ * Before * / # header a {text-decoration:none;border:none;} / * After * / # header a {text-decoration:none;border:none;}

◆ deletes comments. If you must include comments in your CSS file, such as a company's copyright notice, you can enter an exclamation point (!) in the comment to tell YUI Compressor to keep it (see listing 5).

Listing 5. Delete all except necessary comments

/ * Before * / / * This is the main content * / # content {background:#fff url ('images/lb-g.jpg') repeat-x top;min-height:450px; display:inline-block;clear:both;} / * After * / # content {background:#fff url (' images/lb-g.jpg') repeat-x top;min-height:450px; display:inline-block;clear:both;}

◆ deletes the empty declaration. YUI Compressor removes empty declarations from CSS unless they are necessary for normal operation (see listing 6).

Listing 6. Delete empty declaration

/ * Before * / # followicons {margin-left:50px;} # followicons a {} / * After * / # followicons {margin-left:50px;}

◆ performs other optimizations. These optimizations include reducing the leading zeros of decimal numbers and shortening 0 and hexadecimal values (see listing 7).

Listing 7. Perform other optimizations

/ * Before * / body {font-family:Tahoma,Geneva,sans-serif;background-color:# ffee22; margin:0 2000 / After * / body {font-family:Tahoma,Geneva,sans-serif;background-color:#fe2;margin:0;padding:0;}

Taken together, these optimizations made by YUI Compressor to CSS code have made your files much smaller!

Compress JavaScript code

You can use YUI Compressor to compress JavaScript code. Listing 8 shows a file that contains comments and additional formats.

Listing 8. A formatted JavaScript file that is easy to maintain

/ * Creates a cookie on the system with the given name, * value, and for the given number of days. * / function createCookie (name, value, days) {if (days! = null) {var date = new Date (); date.setTime (date.getTime () + (days*24*60*60*1000)); var expires= "; expires=" + date.toGMTString ();} else {var expires= "" } [xss_clean] = name + "=" + value + expires + "; path=/";}

To run YUI Compressor on the JavaScript file, execute the following command:

Java-jar yuicompressor-2.4.2.jar-o functions.min.js functions.js

After YUI Compressor optimizes the file, it looks like listing 9.

Listing 9. Compressed JavaScript file

Function createCookie (b.getTime ()) {if (estrangulated null) {var b=new Date (); b.setTime (b.getTime () + (eBay 24th 60 * 6051000)); var a = "; expires=" + b.toGMTString ()} else {var a = ""} [xss_clean] = c + "=" + dumba+ "; path=/"}

YUI Compressor is added to the Mozilla Rhino (see Resources) project and the JavaScript file is marked with the code in the project. Rhino is a Java implementation that executes JavaScript code and is designed to provide extension points in Java applications that execute JavaScript code by launching these extension points.

Because files are marked with libraries that support JavaScript execution, they will be safely compiled into JavaScript code and executed in the same way as they were written. Other search-and-replace tools are used to narrow the code, such as those that use regular expressions, which will cause errors if the regular expressions used are not fine enough.

The following optimizations are performed in the JavaScript file:

◆ removes whitespace. Remove all unimportant white space, including new lines, from the JavaScript code.

◆ deletes comments. Remove all comments from the JavaScript file except these C-style comments to / *! The sequence begins. If the company copyright or other information must be retained in the file, be sure to use this sequence to include your comments.

◆ renames the Method-scoped variable. Unless you use the-- nomunge option of the YUI Compressor command, YUI Compressor automatically shortens the variable names in the JavaScript file. (leave variable declarations outside the function, assuming they might be used elsewhere). Because variable names in the JavaScript language only need at least one character, you can save a lot of characters for your JavaScript file. Replacing variables slightly confuses the JavaScript code, but since you don't need to modify the version of the code, it shouldn't be a problem.

◆ deletes the semicolon. Like compressing CSS, some unimportant semicolons (;) will be removed from the JavaScript code.

◆ other options. The-- line-break option may be important for detaching files, so this line cannot be too long. (YUI Compressor removes line breaks when optimizing.)

Look at the advantages.

To see the benefits of compression, you can use different tools, two of which are built in browsers, which makes them much easier to use than analysis tools: the developer tool for Google ®Chrome Web browser and the Firebug plug-in for Mozilla ®Firefox. Both tools show you the additional resources to download, as well as the file size and the time it takes to download their browsers.

Figure 2 is an example of a Chrome developer tool that analyzes a page. (to access these tools, click Tools > Developer Tools in your browser.)

Figure 2. Developer tools that ship with the Chrome browser

Figure 3 shows the Firebug plug-in in Firefox analyzing the same page.

Figure 3. Firebug plug-in

If you use an automated tool (described in the next section), you can easily get a URL that uses old files and another URL that contains compressed files (for example, http://localhost/orig and http://localhsot/minified). You can use these tools to do a basic analysis of your web application, and you'll know how different it is to compress your CSS and JavaScript files. The difference may be small at first, but by doing some math, you can see how obvious the long-term effect is to perform optimization than to ignore it.

Automation and integration

To automate compression, add it as a step between file segmentation and test execution. The Ant file in listing 10 demonstrates how to use Ant to automate the operation.

Listing 10. Use Ant automatic Compression

You can also use a shell script, a Windows PowerShell ™script, or a batch file to do this automatically.

Once the file is segmented correctly, you can run your tests according to the segmented code, if you can. If you don't validate your defined JavaScript code through a unit test, you should consider it. See Resources for links to information about UI testing for web applications.

You can also integrate YUI Compressor with IDE, such as Eclipse, so that the build behavior can automatically generate a compressed file for you. The disadvantage of directly integrating Eclipse * is that any single builder added to Eclipse can optimize only one file, unless the builder invokes a script (for example, the Ant script in listing 10) to compress multiple files.

To add YUI Compressor to Eclipse for your project, select the project in Eclipse, and then click Project > Properties to add a new builder to the project. From there, perform the following steps:

Select Builders from the list of properties, and then click New to add a new builder (see figure 4).

Figure 4. Add YUI Compressor as a builder to Eclipse

Select Program, and then click OK (see figure 5).

Figure 5. Add a builder to run the program

Enter Compress as the name of the publish configuration.

Enter the path to your Java folder (for example, / usr/bin/java).

Use the project location as the working directory by clicking Variables and adding ${project_loc}.

Add parameters to the command, including the yuicompressor- {version} .jar file name. In the example shown in figure 6, the JAR file is included in the tool directory of the project.

Figure 6. Add tool parameter

Click the Refresh tab and select Refresh resources upon completion. You just need to refresh the project that contains the source code.

If you build an Ant script to perform compression, you can add a builder to your project to invoke the Ant script in the same way.

At this point, I believe you have a deeper understanding of "how to make Web applications run fast". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

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: 239

*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