A bad jquery may affect the rendering of the entire page or the request takes a long time, such as the page display, I think users do not want to see.
1. Eliminate the need to frequently get jquery objects, which I would like in Java programming:
Bad h = $ (' #element '). Height (); $ (' #element '). CSS (' height ', h-20);//Suggest $element = $ (' #element '); h = $element. Height (); Element.css (' height ', h-20);
2. Get properties from a jquery object with a local variable proxy
3. Replace the direct use event with a binding event:
Bad $first.click (function () { $first. css (' border ', ' 1px solid red '); $first. CSS (' Color ', ' Blue ');}); $first. Hover (function () { $first. css (' border ', ' 1px solid Red ')})//Suggest $first.on (' click ', Function () { $ First.css (' border ', ' 1px solid red '); $first. CSS (' Color ', ' Blue ');}) $first. On (' hover ', function () { $first. css (' border ', ' 1px solid Red ');})
4. Merge repetitive function actions:
Merge function://Bad $first. Click (function () { $first. css (' border ', ' 1px solid red '); $first. CSS (' Color ', ' Blue ');}); Recommended $first. On (' click ', Function () { $first. css ({ ' border ': ' 1px solid red ', ' color ': ' Blue ' });
5. Using links
Bad $second.html (value); $second. On (' click ', Function () { alert (' Hello Everybody ');}); $second. FadeIn (' slow '), $second. Animate ({height: ' 120px '},500);//Recommended $second.html (value); $second. On (' click ', function () { alert (' Hello Everybody ');}). FadeIn (' slow '). Animate ({height: ' 120px '},500);
6. Make some code format optimizations based on 5 to increase readability
Bad $second.html (value); $second. On (' click ', Function () { alert (' Hello Everybody ');}). FadeIn (' slow '). Animate ({height: ' 120px '},500);//recommend $second.html (value) , $second. On (' click ', function () {alert ( ' Hello everybody ') . FadeIn (' slow ') . Animate ({height: ' 120px '},500);
7. Avoid using some error-prone forms:
<a href= "#"/> # here refers to the return page top, although not drill down, but in the project really stepped on the pit. Try to use <a href= "javascript:;" <a href= "javascript:void (0), of course, is also preferred; Void in >//javascript is an operator that specifies that an expression is evaluated but does not return a value.
8. Explanations of some common problems:
The operation is not a button invalidation because onclick= "return false" can only block the URL (or code) execution in the A-tag href attribute, which can be understood as having a page with a label jump failed $ ("#id"). On ("click", Function () {return false;});
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Write high-performance jquery