使用jQuery时的性能优化方案
来源:互联网 发布:在手机上注册淘宝 编辑:程序博客网 时间:2024/04/26 03:19
文章转自:http://blog.csdn.net/cuew1987/article/details/8868420
一、选择器的优化:
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代码最好的方法就是人来测试。但你可以使用一些自动化的工具如Selenium,Funcunit,QUit,QMock来测试你的代码(尤其是插件)。
五、其他
1、使用CDN引入jQuery文件
2、引入最新版本的jQuery文件
3、需要时使用原始javascript,可以更好提高性能
4、压缩JS文件提高加载速度
- 使用jQuery时的性能优化方案
- 使用jQuery时的性能优化方案
- jQuery的性能优化
- jQuery的性能优化
- jQuery的性能优化
- jquery使用简单性能优化
- Unity游戏性能优化时的截图方案分析
- jQuery性能的优化建议
- Jquery的 性能优化小结
- jQuery性能优化的方式
- win2000下oracle817的性能优化方案
- 优化MySQL数据库性能的实际操作方案
- MySQL数据库性能优化的实际操作方案
- Java toString的性能优化方案比较
- Android性能优化的一些方案
- 关于Android性能优化的若干方案
- 《锋利的jQuery》十一、jQuery性能优化
- **系统性能优化方案
- 线程方法synchronized修饰符的作用
- Yahoo!网站性能最佳体验的34条黄金守则——JavaScript和CSS
- 有没有免费怎么把pdf文件转换成excel
- 织梦DedeCMSV5.7程序的memcache配置说明
- 屏幕取色软件ColorPix
- 使用jQuery时的性能优化方案
- CNN(Convolutional Neural Networks)算法
- linux系统管理
- poj-3278
- FastJson--阿里巴巴公司开源的速度最快的Json和对象转换工具
- 解决IllegalStateException: Can not perform this action after onSaveInstanceState
- xcode6 empty application
- 【Linux】Linux查看mac地址方法
- 程序员总结:帮助你早些明白一些道理