使用jQuery时的性能优化方案

 

一、选择器的优化:

1、从ID选择器来继承或者从ID选择器继承来选择多个元素:

var $t=$("#header");
var $p=$("#header p");

2、在class选择器前使用tag标签

jQuery中第二快的选择器就是tag选择器(如$("div"),因为它和直接来自于原生的Javascript方法getElementByTagName()。所以最好总是用tag来修饰class(并且不要忘了就近的ID)

$p=$("#top input.input_txt");

jQuery中class选择器是最慢的,因为在IE浏览器下它会遍历所有的DOM节点。尽量避免使用class选择器。也不要用tag来修饰ID。下面的例子会遍历所有的div元素来查找id为’content’的那个节点:

var $con=$("div#content");

用ID来修饰ID也是画蛇添足:

var $con=$("#top #content");


3、使用子查询

将父对象缓存起来以备将来的使用

var $t=$("#header");
var $p=$t.find("p");

4、优化选择器以适用Sizzle的“从右至左”模型
自版本1.3之后,jQuery采用了Sizzle库,与之前的版本在选择器引擎上的表现形式有很大的不同。它用“从右至左”的模型代替了“从左至右”的模型。确保最右的选择器具体些,而左边的选择器选择范围较宽泛些:

var $t=$(".top div.inputAdd");
而不要使用
var $t=$("div.top .inputAdd");


5. 采用find(),而不使用上下文查找

var divs = $('.testdiv', '#pageBody'); // 2353 on Firebug 3.6 
var divs = $('#pageBody').find('.testdiv'); // 2324 on Firebug 3.6 - The best time 
var divs = $('#pageBody .testdiv'); // 2469 on Firebug 3.6


6、利用强大的链式操作

采用jQuery的链式操作比缓存选择器更有效:

$('li.menu-item')
.click(function () {alert('test click');})                     
.css('display', 'block')                      
.css('color', 'red')                      
.fadeTo(2, 0.7);


7、编写属于自己的选择器

如果你经常在代码中使用选择器,那么扩展jQuery的$.expr[':']对象吧,编写自己的选择器。


二、DOM操作优化:

1、缓存常用的jQuery对象

var $t=$("#top");
$t.click(function(){});


2、进行DOM插入时,循环遍历完之后,再总插入节点

3、检查对象是否存在,如果存在再进行某项操作

4、采用jQuery的内部函数data()来存储状态

在元素上存放数据,返回jQuery对象。

如果jQuery集合指向多个元素,那将在所有元素上设置对应数据。 这个函数不用建立一个新的expando,就能在一个元素上存放任何格式的数据,而不仅仅是字符串。

$("div").data("test", { first: 16, last: "pizza!" });

5、使用jQuery utility函数

$.isFunction,$.isEmpty(),$.isArray(),$.isNumeric(),$.isWindow(),$.isPlainObject(obj);

$.isNumeric("-10");  // true
$.isNumeric(16);     // true
$.isNumeric(0xFF);   // true
$.isNumeric("0xFF"); // true
$.isNumeric("8e5");  // true (exponential notation string)
$.isNumeric(3.1415); // true
$.isNumeric(+10);    // true
$.isNumeric(0144);   // true (octal integer literal)
$.isNumeric("");     // false
$.isNumeric({});     // false (empty object)
$.isNumeric(NaN);    // false
$.isNumeric(null);   // false
$.isNumeric(true);   // false
$.isNumeric(Infinity); // false
$.isNumeric(undefined); // false
 三、事件性能优化

1、使用Event Delegation

指定的元素(属于被选元素的子元素)添加一个或多个事件处理程序,并规定当这些事件发生时运行的函数。

当你在一个容器中有许多节点,你想对所有的节点都绑定一个事件,delegation很适合这样的应用场景。使用Delegation,我们仅需要在父级绑定事件,然后查看哪个子节点(目标节点)触发了事件。当你有一个很多数据的table的时候,你想对td节点设置事件,这就变得很方便。先获得table,然后为所有的td节点设置delegation事件:

$("table").delegate("td", "hover", function(){ $(this).toggleClass("hover"); });

2、使用ready事件简写,这样可以减少代码量

四、测试jQuery

1、标准化你的jQuery代码

你可以用firebug,你也可以用jQuery 快捷函数

/**
* Doom Tweaks for Javascript Projects
*
* @author Dumitru Glavan
* @version 1.1 (16-JUL-2011)
* @requires jQuery
* @link http://dumitruglavan.com
*
* @example: $.l(4,5,6);
* @example: $.time();
* @example: $.lt();$('div')$.lt();
* @example: $.bm('$('div')'); - benchmark your code
* @example: $.mockAjax({mockUrl: '/ajax_mocks'}); - mock your ajax calls
*
* Dual licensed under the MIT and GPL licenses:
*   http://www.opensource.org/licenses/mit-license.php
*   http://www.gnu.org/licenses/gpl.html
*
*/
(function ($) {

    /**
	 * Extend Firebug
	 */
	if (typeof(console) === 'object') {
		/**
		 * Shortcut function for console.log()
		 */
		$.extend($, {
            l: function () {
                for (var i = 0; i < arguments.length; i++) {
                    console.log(arguments[i]);
                }
            }
        });
	}

	/**
	 * Shortcut function for getting timestamp in second (PHP like function time())
	 * @param numeric divideBy - You can switch back to milliseconds by specifying this as 1
	 */
	$.extend($, {
        time: function (divideBy) {
			return ~~(+ (new Date().getTime() / (typeof divideBy === 'undefined' ? 1000 : divideBy)));
		}
    });

	/**
	 * Shortcut function for logging time to the Firebug console
	 * call $.lt() then your code then $.lt() again to get the results
	 */
	$.extend($, {
        lt: function () {
            if (this.ltLastTime == null) {
                return this.ltLastTime = new Date().getTime();
            }
            var diff = new Date().getTime() - this.ltLastTime;
            this.ltLastTime = null;
            $.l(diff);
            return diff;
        },
        ltLastTime: null
	});

	/**
	 * Shortcut function for benchmarking a block of code to the Firebug console
	 * this function will run your code in a for block to create overflow and push the results into Firebug
	 *
	 * @param string benchmarkCode - the block of code you want to benchmark
	 * @param numeric testTime - the number of FOR cicles
	 */
	$.extend($, {
        bm: function (benchmarkCode, testTime) {
            this.testTime = typeof testTime === 'number' ? testTime : 9999;
            $.lt();
            for (var i = 0;i < this.testTime;i++) {
                eval(benchmarkCode);
            }
            $.lt();
        }
	});
        
    /**
     * Mock ajax requests with a prefilter
     *
     */
    $.extend($, {
        mockAjax: function (mockOptions) {
            mockOptions = $.extend({
                mockUrl: '/ajax_mocks'
            }, mockOptions);
            $.ajaxPrefilter(function(options, originalOptions, jqXHR) {
                if (!options.noMock) {
                    options.url = mockOptions.mockUrl + '?ajax_url=' + encodeURIComponent(options.url);
                }
            });
        }
	});
	
})(jQuery);


2、jQuery单元测试

测试JavaSript代码最好的方法就是人来测试。但你可以使用一些自动化的工具如SeleniumFuncunitQUitQMock来测试你的代码(尤其是插件)。

五、其他

1、使用CDN引入jQuery文件

2、引入最新版本的jQuery文件

3、需要时使用原始javascript,可以更好提高性能

4、压缩JS文件提高加载速度

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值