jQuery Optimization

现在jQuery已经出现在很多项目中,然而许多同学忽略了他的性能问题以及代码质量问题,

下面是我对jQuery的一些性能方面的学习.

选择器

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

  1. 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

  2. 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

  3. if possible, right more detail

    //bad

    \(('tag.class .class')
    //good
    \)('.class tag.class')

  4. when you select children, you'd better use find. the best way that cache the parent.

    var parent = $('#parent');

    var children = parent.find('children');

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

  6. 从父元素选择子元素

    • $('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选择器

函数

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

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

代码质量

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

    // 性能差

    $.each(myArray, function(i, item) {

    var newListItem = '

  2. '+item+'
  3. ';

    $('#contain').append(newListItem);

    });

    // 性能好

    var html = '';

    $.each(myArray, function(i, item) {

    html += '

  4. ' + item + '
  5. ';

    });

    $('#contain').html(myHtml);

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

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

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

    var mo = {

    init: function() {

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

    height = $('#element').height();

    $('#element').css('height', height);

    // 好的做法

    $element = $('#element');

    height = $element.height();

    $element.css('height', height);

  9. 尽量少使用全局变量

    $ele = $('#element');

    // 最好使用var

    var $ele = $('#element');

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

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

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

  13. 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源码,只有知道其中的实现原理才能更好的使用它

jQuery Source

编写高性能的jQuery代码的更多相关文章

  1. 编写高效的jQuery代码

    http://www.css88.com/jqapi-1.9/ 编写高效的jQuery代码 最近写了很多的js,虽然效果都实现了,但是总感觉自己写的js在性能上还能有很大的提升.本文我计划总结一些网上 ...

  2. [转]编写高性能的Lua代码

    昨天晚上闲来无事,看室友在电脑上挂机玩游戏,用的一个辅助脚本,以为是lua写的脚本在跑,实际调查发现是按键精灵的脚本. 于是在网上找相关Lua开发游戏脚本的案例,看到一个人的博客,内容很不错,学到了很 ...

  3. 编写高性能的Lua代码

    编写高性能的Lua代码 Posted on2014/04/18· 10 Comments 前言 Lua是一门以其性能著称的脚本语言,被广泛应用在很多方面,尤其是游戏.像<魔兽世界>的插件, ...

  4. 编写高性能的 Lua 代码

    前言 Lua是一门以其性能著称的脚本语言,被广泛应用在很多方面,尤其是游戏.像<魔兽世界>的插件,手机游戏<大掌门><神曲><迷失之地>等都是用Lua来 ...

  5. 如何编写高效的jQuery代码

    jQuery的编写原则: 一.不要过度使用jQuery 1. jQuery速度再快,也无法与原生的javascript方法相比,而且建立的jQuery对象包含的信息量很庞大.所以有原生方法可以使用的场 ...

  6. 如何编写高效的jQuery代码(转载)

    jQuery的编写原则: 一.不要过度使用jQuery 1. jQuery速度再快,也无法与原生的javascript方法相比,而且建立的jQuery对象包含的信息量很庞大.所以有原生方法可以使用的场 ...

  7. 程序员笔记|如何编写高性能的Java代码

    一.并发 Unable to create new native thread …… 问题1:Java中创建一个线程消耗多少内存? 每个线程有独自的栈内存,共享堆内存 问题2:一台机器可以创建多少线程 ...

  8. (转载)编写高效的jQuery代码

    原文地址:http://www.cnblogs.com/ppforever/p/4084232.html 最近写了很多的js,虽然效果都实现了,但是总感觉自己写的js在性能上还能有很大的提升.本文我计 ...

  9. 如何编写好的jQuery代码

    本文就是自己看,如果您不小心进到了这里,请看源处,是这个作者翻译的:http://blog.sae.sina.com.cn/archives/4157 讨论jQuery和javascript性能的文章 ...

随机推荐

  1. Parallel Programming AND Asynchronous Programming

    https://blogs.oracle.com/dave/ Java Memory Model...and the pragmatics of itAleksey Shipilevaleksey.s ...

  2. Debugging and performance,ETW

    http://blogs.technet.com/b/serverandtools/ https://channel9.msdn.com/Shows/Defrag-Tools http://blogs ...

  3. 常用的正则表达式C#工具类

    Regex类实现了一些特殊功能数据检查,正则表达式的一些常用的功能,集成至该类中. public class RegexDao { private RegexDao() { } private sta ...

  4. angular学习笔记(二十四)-$http(2)-设置http请求头

    1. angular默认的请求头: 其中,Accept 和 X-Requested-With是$http自带的默认配置 Accept:application/json,text/plain       ...

  5. python地址解析经纬度,城市

    1.地址列表 1.txt 上海市普陀区梅川路299-301号 浙江省杭州市拱墅区丰登路305-311号1层 江苏省南京市鼓楼区碧树园86号101室 浙江省宁波市江北区范江岸路38弄6号-10号1层商铺 ...

  6. php phpmail发送邮件的效果

    方法一: /*                                                                                * 发送邮件 原 smtp ...

  7. LeetCode: Roman to Integer 解题报告

    Roman to IntegerGiven a roman numeral, convert it to an integer. Input is guaranteed to be within th ...

  8. tomcat 启动 报错Neither the JAVA_HOME nor the JRE_HOME environment variable is definedtemp

    catalina.sh 加入环境 export JAVA_HOME=/usr/local/jdk1.7.0_79 export CATALINA_HOME=/home/sa/webserver/tom ...

  9. ajaxupload 异步上传工具

    基于jquery库异步上传的jquery插件 $.ajaxFileUpload({ url:(baseURL+'/common/fileUploadAct!fileUpload.action?clas ...

  10. Cannon

    Description In Chinese Chess, there is one kind of powerful chessmen called Cannon. It can move hori ...