15 JavaScript best practices summary_javascript tips
WBOYOriginal
2016-05-16 17:26:16971browse
This document organizes most of the generally accepted, or less controversial, JavaScript best practices. Some obvious common sense will not be discussed (for example, use objects to support recognition judgments instead of browser recognition judgments; for example, do not nest too deeply). The items are sorted roughly from high to low importance. Place external JavaScript files at the bottom of the HTML Our goal is the same: display content as quickly as possible for the user. When loading a script file, HTML will stop parsing until the script is loaded. As a result, users may be looking at a blank screen for long periods of time, with nothing seemingly happening. If your JavaScript code just adds some functionality (such as a button click action), then feel free to put the file reference at the bottom of the HTML (just before
), and you will see a significant speed increase. If it is a script file used for other purposes, it needs to be carefully considered. Regardless, this is undoubtedly a place well worth considering. Optimize loop Loop through an array
//This bad code will calculate the length of the array every time it enters the loop var names = ['George','Ringo','Paul','John'] ; for(var i=0;idoSomeThingWith(names[i]); }
//In this case, it will only be calculated once var names = ['George' ,'Ringo','Paul','John']; var all = names.length; for(var i=0;idoSomeThingWith(names[i] ); }
Copy code The code is as follows: //This is shorter
Copy code The code is as follows: //The bad thing about this code is that it puts the variable declaration in the loop body, and the variable will be created every time it loops
//Repeated variable name many times var cow = new Object(); cow.colour = 'brown'; cow.commonQuestion = 'What now?'; cow.moo = function(){ console.log(' moo'); } cow.feet = 4; cow.accordingToLarson = 'will take over the world';
//A better way to write it is like this var cow = { colour:'brown', commonQuestion:'What now?', moo:function(){ console.log('moo); }, feet:4, accordingToLarson:'will take over the world' };
//The array name is repeated many times var aweSomeBands = new Array(); aweSomeBands[0] = 'Bad Religion'; aweSomeBands[1] = 'Dropkick Murphys'; aweSomeBands[2] = 'Flogging Molly'; aweSomeBands[3] = 'Red Hot Chili Peppers'; aweSomeBands[4] = 'Pornophonique';
Avoid mixing other technologies CSS: Suppose there is an input box on our page that must be filled in (with class "mandatory"). If no data is entered into it, red will be added around it. frame.
//A piece of code mixed with other technologies will do this : var f = document.getElementById('mainform'); var inputs = f.getElementsByTagName('input'); for(var i=0,j=inputs.length;iif(inputs[i].className === 'mandatory' && inputs[i].value === ''){ inputs[i].style.borderColor = '#f00'; inputs[i].style.borderStyle = 'solid'; inputs[i].style.borderWidth = '1px'; } }
//A good piece of code will do this: Leave the stylization to CSS var f = document.getElementById('mainform'); var inputs = f.getElementsByTagName('input'); for(var i=0,j= inputs.length;iif(inputs[i].className === 'mandatory' && inputs[i].value === ''){ inputs[ i].className = ' error'; } }
HTML: Suppose we have a lot of HTML content that needs to be loaded using JavaScript, then use Ajax to load separate files instead of processing the DOM through JavaScript. The latter will make the code difficult to process and cause compatibility that is difficult to maintain. question. Validate JavaScript code Browsers can be very forgiving when it comes to JavaScript code, but I advise you not to rely on the browser's parsing capabilities and therefore develop lazy coding habits. The easiest way to check the quality of your code is through JSLint, an online JavaScript verification tool. "JSLint takes a JavaScript source and scans it. If it finds a problem, it returns a message describing the problem and an approximate location within the source. The problem is not necessarily a syntax error, although it often is. JSLint looks at some style conventions as well as structural problems. It does not prove that your program is correct. It just provides another set of eyes to help spot problems.” – JSLint Documentation Use a simpler format to write innerscript
Always check data To check all data entered by your methods, on the one hand for security, On the other hand it is also for usability. Users enter incorrect data anytime and anywhere. It's not because they're stupid, it's because they're busy and think differently than you do. Use the typeof method to check whether the input your function accepts is legal.
//If the type of members is not an array, then the following The code will throw an error function buildMemberList(members){ var all = members.length; var ul = document.createElement('ul'); for(var i=0; i
//Good habits It is to check whether the parameter is an array function buildMemberList(members){ //The typeof of the array is object, so if you want to determine whether it is an array, you can test whether it has a function that is only available for arrays: slice if(typeof members === 'object' && typeof members.slice === 'function'){ var all = members.length; var ul = document.createElement('ul' ); for(var i=0;i
Another security risk is to use data directly from the DOM. For example, your function gets the user name from the user name input box. Something but single or double quotes in the username may cause your code to crash Avoid global variables Global variables and global functions are very bad. All JavaScript contained in the page runs in the same domain, so if you declare global variables or global functions in your code, the variables and functions of the same name in the script files loaded in the subsequent code will be overwritten. Yours.
//If variables and functions do not need to be referenced "outside", then you can use an unnamed method to wrap them all. (function(){ var current = null; function init(){...} function change(){...} function verify(){.. .} })();
//If variables and functions need to be referenced "outside", you need to put your variables and functions in a "namespace" //We use a function as a namespace here instead of a var, because declaring function in the former is simpler and can protect private data myNameSpace = function(){ var current = null; function init(){...} function change (){...} function verify(){...} //All functions and attributes that need to be called outside the namespace must be written in return return{ init :init, //You can even name an alias for functions and properties set:change } }();
when declaring variables , always use var Variables in JavaScript may be global or local, and it will be more intuitive to declare them with var.
//Confusing problems caused by not using var in function var i=0; // This is good - creates a global variable function test() { for (i=0; i<10; i ) { alert("Hello World !"); } } test(); alert(i); // The global variable i is now 10!
//The solution is to declare the variable in the function and also use var function test( ) { for (var i=0; i<10; i ) { alert("Hello World!"); } }
Use prefixes to convert strings into numbers In JavaScript, the " " operator is used to add numbers and concatenate strings. If you need to ask for the sum of several values in a form, then using may cause problems.
//The code that will cause problems < form name="myform" action="[url]">
function total() { var theform = document.forms["myform"]; var total = theform. elements["val1"].value theform.elements["val2"].value; alert(total); // This will alert "12", but what you wanted was 3! }
//Add " in front of the string ”, which is a hint to JavaScript: this is a number, not a string function total() { var theform = document.forms["myform"]; var total = ( theform. elements["val1"].value) ( theform.elements["val2"].value); alert(total); // This will alert 3 }
Avoid using the eval() method The eval() method in JavaScript is a method to calculate/run any code as an object at runtime. In fact, due to security reasons, eval() should not be used in most cases. There is always a more "correct" way to accomplish the same job. The basic rule is, eval is evil, don't use it at any time unless you are a veteran and know you have to do it. for in statement When traversing all the items in an object, it is very convenient to use the for in statement. But sometimes we don't need to traverse the methods in the object. If not, we can add a filter.
//This code looks even more wrong. At first glance, it seems that the following sentences have been executed //In fact, only x=false is in if if(someVariableExists) x = false anotherFunctionCall();
So, the principles to remember are: 1. Never omit a semicolon; 2. Do not omit curly braces unless they are on the same line middle.
If you use dot notation to obtain the properties of the object, the property name is hard-coded and cannot be changed at runtime; if you use square brackets, JavaScript will obtain the square brackets The inner value is then calculated to obtain the attribute name. In other words, using square brackets, the attribute name can be hard-coded, or it can be a variable or function return value.
//This way there is no Question MyObject["value" i]
Assuming that JavaScript will be disabled I know that such an assumption will hurt the feelings of JavaScript developers, but in the current situation of unclear data We should make this assumption to be on the safe side. This is an important part of progressive enhancement. Use JavaScript libraries There are many very popular JavaScript libraries now, such as YUI, jQuery, and Dojo. Their disadvantage is that they need to download an additional file, but their advantages are more: greater compatibility; the code is simpler and easier to understand. There are many good libraries out there, but you shouldn't use them all in one project because there may be compatibility issues. Just choose one you are used to. Don’t forget that native JavaScript is undoubtedly faster. If it is used on a small scale, it is best to use native JavaScript.
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn