Brief introduction:

A few months ago I was given a new development assignment to add some new functionality to an old Web page. In the process of development, I found that there are many common inappropriate writing methods in the old code. Combined with these problems, how to write a better, more standardized, more maintainable code is the content of this article.

First I looked at the HTML code for the Web page and found some typical problems:

  • HTML pages contain a lot of Javascript and CSS code
  • HTML pages reference a large number of external Javascript files and CSS files

Let’s talk about each of these questions one by one.



HTML pages contain a lot of Javascript and CSS code

A normal Web page usually consists of the following three parts: HTML, CSS, and Javascript. HTML is data, CSS is responsible for style, and Javascript is responsible for interaction. The relationship among the three is shown as follows:

As you build your Web pages, try to keep these three loosely coupled, and not all at once. Small changes in one layer require changes in two other layers. The first step is to isolate these three parts at the file level and import Javascript and CSS by importing files into the HTML.

To achieve loose coupling of the three, the following points need to be noted in development:

  • Do not include Javascript in your CSS code
  • Do not include CSS in your Javascript code
  • Do not include Javascript in your HTML code
  • Do not include HTML in Javascript

Do not include Javascript in CSS code. This refers to the careful use of computable styles in CSS code, such as EXPRESSION in IE 8, CALc in CSS3, etc. From the point of view of use, they are all very powerful. From the point of view of code maintenance, they are not recommended. When bugs occur, you need to Check both Javascript and CSS code.

Do not include CSS in your Javascript code. We often need to dynamically change the style of a Dom element in Javascript, often writing the following code:

element.style.color = 'red';Copy the code
Such code results in the need to retrieve the full text of the RED keyword in your Javascript code when requirements change, in case you miss anything. Recommended practices are as follows:

// Define the style type in the CSS file. Red-class {color: red; } // Change the style in Javascript element.className += "red-class"; // jQuery $(element).addClass("red-class");Copy the code

Manipulating the Class of a Dom object in Javascript to change the style, you can simply adjust the CSS file when the requirements change.

Don’t include Javascript in your HTML code:

Copy the code
The following code is recommended:

var btn = document.getElementById('mybutton');
btn.addEventListener("click", do);Copy the code
Do not include HTML in your Javascript code:

var div = document.getElementById("my-div");
div.innerHTML = "

Error

Invalid e-mail address.

";Copy the code
It’s difficult to completely isolate HTML from Javascript code, and this can be a tradeoff based on the actual situation. Javascript Template technology is an effective way to separate HTML from Javascript code. Here is how jQuery Template is used:

// HTML // Javascript // Create an array of books var books = [{title: "ASP.NET 4 Unleashed", price: 37.79, picture: "AspNet4Unleashed.jpg" }]; // Render the books using the template $("#bookTemplate").tmpl(books).appendTo("#bookContainer"); function formatPrice(price) { return "[ DISCUZ_CODE_5 ]quot; + price.toFixed(2); }Copy the code

Secondly, HTML pages reference a large number of external Javascript files and CSS files

HTML pages reference a large number of external Javascript files and CSS files. We know that each reference to external files or will cause an HTTP request, and the cost of an HTTP request is actually very high. The following is the whole process of HTTP request:

Var foo = 10; // Declare foo = 10 without using var; window.foo = 10;Copy the code

After the TCP connection is established, the browser sends an HTTP request to the Server. After the Server processes the request, the Server returns the result to the browser. Finally, the TCP connection is disabled. The cost of the entire HTTP request is still high.


In addition, browsers have a limit on the number of concurrent HTTP requests, which varies from one browser to four.


When HTML pages reference a large number of external Javascript and CSS files, we can consider merging and compressing Javascript and CSS files to reduce the number of HTTP requests and HTTP results.


Grunt is a task-based command line building tool for JavaScript projects. Grunt combines multiple files into a single file and compresses them. Grunt is platform-free and can be used to configure tasks for any front-end project. Grunt has extensive community support and many existing plugins.

In addition, if you are an ASP.NET project, ASP.NET 4.5 adds Bundle, which incorporates compressed Javascript and CSS through Bundle technology.


Javascript code global variables

After looking at the HTML code, I took a look at the main Javascript code of the page and found that the main problem was that the Javascript code introduced too many global variables. JavaScript global variables can be handy in small programs, but they quickly become unwieldy as programs get bigger. Because a global variable can be changed at any time by any part of the program, the behavior of the program is greatly complicated. The use of global variables in a program reduces its reliability.

There are three ways to define Javascript:

(function(win) {
    "use strict";
    var doc = win.document;
    // declare other variables here
    // other code goes here
}(window));Copy the code

The second of these implicitly declares global variables, which is especially important.

We should use global variables as little as possible, and jQuery provides only two global variables: $, jQuery. Is it possible to introduce zero global variables after injecting Javascript into an HTML page?

You can do this by executing the function immediately, as shown in the following code:

Var module1 = (function(){var _count = 0; Var m1 = function(){//... }; Var m2 = function(){//... }; Return {m1: m1, m2: m2}; }) ();Copy the code
This will introduce only one global variable, module1, which is well encapsulated and whose internal variable, “_count,” is not externally accessible. There are also some other minor issues with the whole page, which I won’t go over here. Talking about old code for a long time, in fact, there is no bias against old code, because whether it is beautiful or ugly, are serving the system, are generating value. We’re just looking for better code, more readable, more maintainable code.



Did this article help you? Welcome to join the front End learning Group wechat group: