编写高性能的jQuery代码

简介: 编写高性能的jQuery代码

选择器



选择器是jQuery中的核心功能,选择同一个DOM元素我们可以使用不同的方法。但是哪一种是最快的呢?


if possible, please use more id selector. id selector is used javascript method getElementById
//bad
('#id selector')    
//good('#id')
caution: don't use tag to decorate id selector
Before using class selector, you'd better add tag. that's is used javascript method getElementsByTagName
//bad
(′.class′)//good('tag.class')
caution: class selector is the slower selector, use less
if possible, right more detail
//bad
(′tag.class.class′)//good('.class tag.class')
when you select children, you'd better use find. the best way that cache the parent.
var parent = $('#parent');
var children = parent.find('children');


最慢选择器:伪类选择器和属性选择器,新的浏览器增加了querySelector()和querySelectorAll()方法,可能会使这两类选择器性能提升


从父元素选择子元素


$('child', parent)这种选择其实会执行parent.find('child'),排名第二
$('child', (′parent′))这种选择会别转成('parent').find('child'),排名第三
$('#parent child')


这种选择适合选择多级子元素,排名第六


$('#parent > child')


这种选择和上面的相同,排名第五


parent.children(′child′)这种选择会被转换成.sibling(),排名第四


$parent.find('child')


这种选择会被转成getElementById,getElementByName,getElementByTagName等javascript原生语法,所以速度最快,排名第一


总结:


ID选择器是最快的选择器,建议多用。然后是标签选择器,其次是class选择器

 

函数


使用jQuery的内部函数data()来存储状态


尽量使用on方法来绑定事件,因为任何绑定方法都是最终使用on来实现的


代码质量


不要在循环中直接操作 DOM:


// 性能差
$.each(myArray, function(i, item) {
var newListItem = '
'+item+'
';
('#contain').append(newListItem);  
});  
// 性能好  
var html = '';.each(myArray, function(i, item) {
html += '
' + item + '
';
});
$('#contain').html(myHtml);


对数组循环时,缓存数组长度


for(var i = 0, len = array.length; i < len; i++) {
}

       

尽量少使用匿名函数,最好使用类封装


var mo = {
init: function() {
    }        
};


缓存变量,DOM遍历最消耗性能,所以尽量将重用的元素缓存


height = ('#element').height();('#element').css('height', height);
// 好的做法
element=('#element');
height = element.height();element.css('height', height);
尽量少使用全局变量
ele=('#element');
// 最好使用var
var ele=('#element');


简单的语句可以使用原生的javascript,因为jQuery最终执行的也是原生的


使用链式写法,因为使用链式写法jQuery自动缓存每一步的结果,因此比非链式写法要快

尽量少使用$.each进行循环,使用原生javascript的for和while来进行

jQuery大部分方法都有两种,例如:().each与.each


$().each是基于jQuery对象的,jQuery对象会占用很多资源,因为他包含很多属性和方法        

$.each是基于jQuery方法的,不会占用太多资源,所以尽量使用这种方式    


10.尽量使用.ajax,少使用.get(),.getJSON(),.post(),因为他们最终也是用的$.ajax()


减少代码嵌套:



减少代码嵌套,对于阅读和维护代码来时都是有益的,通过deffer我们可以减少代码的嵌套


***第一种:***        
        var request = function() {        
            var defer = $.Deferred();        
            $.ajax({url:'data/test.json'})        
            .done(function(data){        
                defer.resolve(data);        
            });        
            return defer;        
        };      
        $.when(request())
        .then(function(data) {
            console.log(data);
        });        
      ***第二种:***        
        var request = function() {        
            return $.ajax({url:'data/test.json'});        
        };
        $.when(request())
        .then(function(data) {
            console.log(data);
        });        
      ***第三种:***        
        $.when($.ajax(url:'data/test.json'))
        .then(function(data) {
            console.log(data);
        });

 

建议多阅读几遍jQuery源码,只有知道其中的实现原理才能更好的使用它

相关文章
|
1月前
|
JavaScript
jQuery幸运大转盘抽奖活动代码
jQuery幸运大转盘抽奖活动代码
43 7
jQuery幸运大转盘抽奖活动代码
|
7月前
|
JavaScript
基于jQuery的公告无限循环滚动实现代码
基于jQuery的公告无限循环滚动实现代码
36 0
|
9月前
|
JavaScript 开发者
|
9月前
|
JavaScript
jQuery 五角星评分案例(详细代码)
jQuery 五角星评分案例(详细代码)
75 0
|
5天前
|
JavaScript 前端开发
杨校老师课堂之Web前端JS类库_JQuery案例[效果图与代码齐全]
杨校老师课堂之Web前端JS类库_JQuery案例[效果图与代码齐全]
12 0
|
1月前
|
JavaScript 前端开发
jquery酷炫的马赛克图片还原动画代码
jquery酷炫的马赛克图片还原动画代码,jquery马赛克图片动画,js酷炫图片代码,马赛克图片js还原效果,js图片分散汇聚效果素材
59 1
|
1月前
|
存储 移动开发 JavaScript
jQuery 根据 css 类筛选 DOM 元素的代码
jQuery 根据 css 类筛选 DOM 元素的代码
|
1月前
|
JavaScript 前端开发 索引
jQuery学习教程,写更少的代码,做更多的事情(二)
jQuery学习教程,写更少的代码,做更多的事情(二)
|
1月前
|
JavaScript
jQuery模态框弹窗提示代码
jQuery模态框弹窗提示代码
24 1
jQuery模态框弹窗提示代码
|
1月前
|
JSON JavaScript 数据格式
jQuery 树型菜单完整代码
jQuery 树型菜单完整代码