BKJIA exclusive Article] JavaScript is an extremely powerful and flexible scripting language, but for many people, "flexibility" also means easy mistakes. Here I will introduce the best practices of five JavaScript types, which can be applied in any JavaScript project and have high scalability.
BKJIA related articles: Seven JavaScript skills that should have been known
First, you must keep the code concise, clean, and high-quality comments. They are not unique to JavaScript, but many people do not pay attention to them. Compared with the comments of the Code itself, it is equally important to clarify the functions of each piece of code.
Second, save your JavaScript in an external file. The correct method to reference an external JS file is as follows:
- <script type="text/javascript" src="script.js"></script>
Third, separate your JavaScript scripts from the presentation layer. An example of adding an onclick time from JavaScript is as follows:
- var div = document.getElementById('div');
- div.onclick = new Function("processClick(this)");
Fourth, properly process and define variables. Many programmers do not properly define the scope of variables when programming, but simply use var.
Fifth, we should think carefully before using JavaScript, rather than putting JavaScript first. According to different users, many people may disagree with my ideas, but I still want to say: we should consider a small number of users, with an estimated 10%-of Web users not using JavaScript scripts) and reduce the use of JavaScript. In my opinion, JavaScript is like a helper tool, and we should not rely too much on it. Just like in the following example, those are the most important elements in the web page.
- <a href="javascript:processClick()">link</a>
- <a href="#" onclick="javascript:processClick()">link</a>
When a JavaScript script is disabled, the user clicks any of the links and nothing will happen. However, if the following code is used, even if JavaScript is disabled, they can still browse.
- <a href="link.html" onclick="processClick(); return false;">link</a>
Title: 5 JavaScript Best Practices Author: Michael
Address: http://www.leigeber.com/2008/04/5-javascript-best-practices