Good code can lead to speed improvements. Fast rendering and responsiveness means a better user experience.
First, keep in mind that jquery is JavaScript. This means that we should take the same coding conventions, style guides and best practices.
First of all, if you're a novice JavaScript, I suggest you read the 24 best practices for JavaScript beginners , a high-quality JavaScript tutorial that you'd better read before contacting jquery.
When you are ready to use jquery, I strongly recommend that you follow these guidelines:
Cache variables
DOM traversal is expensive, so try to cache the elements that will be reused.
- Bad
- H = $ (' #element '). Height ();
- $ (' #element '). CSS (' height ', h-20);
- Suggestions
- $element = $ (' #element ');
- h = $element. Height ();
- $element. css (' height ', h-20);
Copy Code
Avoid global variables
jquery, like JavaScript, is generally preferable to ensure that your variables are within the scope of the function.
- Bad
- $element = $ (' #element ');
- h = $element. Height ();
- $element. css (' height ', h-20);
- Suggestions
- var $element = $ (' #element ');
- var h = $element. Height ();
- $element. css (' height ', h-20);
Copy Code
Using the Hungarian nomenclature
Prefix the variable with $ to make it easy to identify the jquery object.
- Bad
- var first = $ (' #first ');
- var second = $ (' #second ');
- var value = $first. val ();
- Recommendation-add $ prefix to jquery objects
- var $first = $ (' #first ');
- var $second = $ (' #second '),
- var value = $first. val ();
Copy Code
Using the var chain (single var mode)
To combine multiple VAR statements into one statement, I recommend that you put unassigned variables behind.
- Var
- $first = $ (' #first '),
- $second = $ (' #second '),
- Value = $first. val (),
- K = 3,
- cookiestring = ' Somecookiesplease ',
- I
- J
- MyArray = {};
Copy Code
Please use ' on '
In the new version of jquery, Shorter on ("click") is used to replace functions like Click (). In the previous version, on () is bind (). The preferred method of on () attaching event handlers since the jquery 1.7 release. However, for consistency reasons, you can simply use the on () method.
- Bad
- $first. Click (function () {
- $first. CSS (' border ', ' 1px solid red ');
- $first. CSS (' Color ', ' blue ');
- });
- $first. Hover (function () {
- $first. CSS (' border ', ' 1px solid red ');
- })
- Suggestions
- $first. On (' click ', function () {
- $first. CSS (' border ', ' 1px solid red ');
- $first. CSS (' Color ', ' blue ');
- })
- $first. On (' hover ', function () {
- $first. CSS (' border ', ' 1px solid red ');
- })
Copy Code
Thin JavaScript
In general, it is best to combine functions as much as possible.
- Bad
- $first. Click (function () {
- $first. CSS (' border ', ' 1px solid red ');
- $first. CSS (' Color ', ' blue ');
- });
- Suggestions
- $first. On (' click ', function () {
- $first. CSS ({
- ' Border ': ' 1px solid red ',
- ' Color ': ' Blue '
- });
- });
Copy Code
Chained operation
The chained operation of the jquery implementation method is very easy. Use this point below.
- Bad
- $second. HTML (value);
- $second. On (' click ', function () {
- Alert (' Hello everybody ');
- });
- $second. FadeIn (' slow ');
- $second. Animate ({height: ' 120px '},500);
- Suggestions
- $second. HTML (value);
- $second. On (' click ', function () {
- Alert (' Hello everybody ');
- }). FadeIn (' slow '). Animate ({height: ' 120px '},500);
Copy Code
Maintain the readability of your code
Along with the streamlining of code and the use of chaining, the code can be difficult to read. Adding a shrink and line break can be a good result.
- Bad
- $second. HTML (value);
- $second. On (' click ', function () {
- Alert (' Hello everybody ');
- }). FadeIn (' slow '). Animate ({height: ' 120px '},500);
- Suggestions
- $second. HTML (value);
- $second
- . On (' click ', function () {alert (' Hello Everybody ');})
- . FadeIn (' slow ')
- . Animate ({height: ' 120px '},500);
Copy Code
Select short-Circuit evaluation
A short-circuit evaluation is an expression that evaluates from left to right, with && (logical AND) or | | (logical OR) operators.
- Bad
- function Initvar ($myVar) {
- if (! $myVar) {
- $myVar = $ (' #selector ');
- }
- }
- Suggestions
- function Initvar ($myVar) {
- $myVar = $myVar | | $ (' #selector ');
- }
Copy Code
Choose a shortcut
One way to streamline your code is to take advantage of coding shortcuts.
- Bad
- if (Collection.length > 0) {..}
- Suggestions
- if (collection.length) {..}
Copy Code
Separation of elements in heavy operations
If you are going to do a lot of work on DOM elements (setting multiple properties or CSS styles consecutively), it is recommended that you first detach the elements and then add them.
- Bad
- Var
- $container = $ ("#container"),
- $containerLi = $ ("#container Li"),
- $element = null;
- $element = $containerLi. First ();
- //... Many complex operations
- Better
- Var
- $container = $ ("#container"),
- $containerLi = $container. Find ("Li"),
- $element = null;
- $element = $containerLi. First (). Detach ();
- //... Many complex operations
- $container. Append ($element);
Copy Code
Memorizing skills
You may have a lack of experience with the methods in jquery, be sure to review the documentation, and there may be a better or faster way to use it.
- Bad
- $ (' #id '). Data (Key,value);
- Recommended (efficient)
- $.data (' #id ', key,value);
Copy Code
Using the parent element of a subquery cache
As mentioned earlier, Dom traversal is an expensive operation. A typical practice is to cache the parent element and reuse those cached elements when the child element is selected.
- Bad
- Var
- $container = $ (' #container '),
- $containerLi = $ (' #container Li '),
- $containerLiSpan = $ (' #container Li span ');
- Recommended (efficient)
- Var
- $container = $ (' #container '),
- $containerLi = $container. Find (' Li '),
- $containerLiSpan = $containerLi. Find (' span ');
Copy Code
Avoid Universal selectors
It is very bad to put a generic selector in a descendant selector.
- Bad
- $ ('. Container > * ');
- Suggestions
- $ ('. Container '). Children ();
Copy Code
Avoid implicit universal selectors
Universal selectors are sometimes implicit and not easily discoverable.
- Bad
- $ ('. Someclass:radio ');
- Suggestions
- $ ('. SomeClass input:radio ');
Copy Code
Refine selectors
For example, the ID selector should be unique, so there is no need to add additional selectors.
- Bad
- $ (' Div#myid ');
- $ (' Div#footer a.mylink ');
- Suggestions
- $ (' #myid ');
- $ (' #footer. MyLink ');
Copy Code
Avoid multiple ID selectors in this emphasis, the ID selector should be unique, no additional selectors need to be added, and more than one descendant ID selector is required.
- Bad
- $ (' #outer #inner ');
- Suggestions
- $ (' #inner ');
Copy Code
Stick to the latest version
The new version is usually better: more lightweight and more efficient. Obviously, you need to consider the compatibility of the code you want to support. For example, the 2.0 version does not support IE 6/7/8. It is important to discard deprecated methods that focus on each new version and avoid using them as much as possible.
- Bad
- $ (' #outer #inner ');
- Suggestions
- $ (' #inner ');
Copy Code
Leveraging CDN
Google's CND ensures that the most recent cache is selected from the user and responds quickly. (Use Google CND, please search the address, where the address can not be used, recommended by the jquery website CDN).
Combine jquery and JavaScript native code if necessary
As mentioned above, jquery is JavaScript, which means that what you can do with jquery can also be done using native code. Native code (or vanilla) may be less readable and maintainable than jquery, and the code is longer. But it also means more efficient (often closer to lower-level code readability and higher performance, for example: compilation, which of course requires more powerful talent). Keep in mind that no framework can be smaller, lighter, and more efficient than native code (note: The test link is invalid and the test code can be searched online). Given the performance differences between vanilla and jquery, it is highly recommended to absorb the essence of both, using (possibly) and jquery equivalent native code .
Explore the mysteries of efficient jquery