您的位置:首页 > Web前端 > JQuery

javascript之jQuery 性能优化技巧

2013-12-01 19:44 621 查看

使用最新版本的jQuery类库

jQuery 1.7 重构了事件委托,性能节省了一半左右

使用缩写,$(function(){..})代替$(document).ready()

使用合适的选择器

$("#id") 使用id来定位DOM元素可以提高性能,或$("#content").find("div"),调用find()方法,建议从最近的ID元素开始往下搜索
$("p"),$("div"),$("input")使用标签选择器的性能
$(".class"),$("[attribute=value]"),对性能的影响比较大
可以使用http://jsperf.com/查看性能区别
尽量使用ID选择器,给选择器指定上下文

缓存变量

像java开发中不要随意的创建对象一样,可以帮助你有效的提高代码运行性能,不要让相同的选择器在你的代码上出现多次

window.$my={
	head : $("head").
	traffic_light : $("#traffic_light").
	traffic_button : $("traffic_button")
};
function do_something(){
	var script=document.createElement("script");
	$my.head.append(script);
}

减少DOM操作

将整个元素字符串插入DOM之前,全部创建好.

***jQuery插件

:(function($){
	$.fn.yourPluginName=function(){
		// Your code goes here
		return this;
	}
})(jQuery);

使用join()来拼接字符串

join()比'+'有助于长字符串处理的时候

使用原生的javascript方法

1.jQuery方式判断
var $cr=$("#cr");
$cr.click(function(){
	if($cr.is(":checked")){//jQuery方式判断
		alert("hello");
	}
})
2.javascript方式判断
var $cr=$("#cr");//jQuery对象
var cr=$cr.get(0);//DOM 对象,获取 $cr[0]
$cr.click(function(){
	if(cr.checked){ //原生的javascript方式判断
       alert("hello")
	}
})

$(this).css("color","red")
可优化为
this.style.color="red";

$("<p></p>");
可优化为
$( document.createElement("p") );

压缩JavaScript

可以使用JSMin,YUI Compressor,Google Closure Compiler 和UglifyJS压缩JS的体积

新窗口打开页面

$(document).ready(function() {  
     //例子1: href=”http://”的超链接将会在新窗口打开链接 
     $('a[href^="http://"]').attr("target", "_blank");  
 
     //例子2: rel="external"的超链接将会在新窗口打开链接  
     $("a[rel$='external']").click(function(){  
          this.target = "_blank";  
     });  
});

判断浏览器类型,官方推荐使用$.support代替$.browser的检测方式

$(document).ready(function() {  
	// Firefox 2 and above  
	if ($.browser.mozilla && $.browser.version >= "1.8" ){  
		// do something  
	}    
	// Safari  
	if( $.browser.safari ){  
		// do something  
	}    
	// Chrome  
	if( $.browser.chrome){  
		// do something  
	}    
	// Opera  
	if( $.browser.opera){  
		// do something  
	}    
	// IE6 and below  
	if ($.browser.msie && $.browser.version <= 6 ){  
		alert("ie6")
	}    
	// anything above IE6  
	if ($.browser.msie && $.browser.version > 6){  
		alert("ie6以上")
	}  
});

返回头部滑动动画

jQuery.fn.scrollTo = function(speed) {
	var targetOffset = $(this).offset().top;
	$('html,body').stop().animate({scrollTop: targetOffset}, speed);
	return this;
}; 
// use
$("#goheader").click(function(){
	$("body").scrollTo(500);
	return false;
});

获取鼠标位置

$(document).ready(function () { 
	$(document).mousemove(function(e){  
		$('#XY').html("X : " + e.pageX + " | Y : " + e.pageY);  
	});
});

判断元素是否存在

$(document).ready(function() {  
	if ($('#XY').length){  
	   alert('元素存在!')
	}else{
	   alert('元素不存在!')
	}
});

点击div也可以跳转

$(document).ready(function() {	
	$("div").click(function(){  
		window.location=$(this).find("a").attr("href"); 
		return false;  
	}); 
});

根据浏览器大小添加不同的样式

$(document).ready(function() {  
	function checkWindowSize() {  
		if ( $(window).width() > 900 ) {  
			$('body').addClass('large');  
		}else{  
			$('body').removeClass('large');  
		}  
	}  
	$(window).resize(checkWindowSize);  
});


设置div在屏幕中央

$(document).ready(function() {  
   jQuery.fn.center = function () {  
	  this.css("position","absolute");  
	  this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");  
	  this.css("left", ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px");  
	  return this;  
	}  
	//use
	$("#XY").center();  
});

回车提交表单

$(document).ready(function() {  
     $("input").keyup(function(e){
		    if(e.which=="13"){
			   alert("回车提交!")
		    }
		})
});

设置全局Ajax参数

$(document).ready(function() { 
	$('#send1').click(function() {
		$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?tags=car&tagmode=any&format=json&jsoncallback=?",function(data){
					  $("#resText1").empty();
					  $.each(data.items, function( i,item ){
							$("<img/> ").attr("src", item.media.m ).appendTo("#resText1");
							if ( i == 3 ) { 
								return false;
							}
					  });
				 }
		); 
   });

	$.ajaxPrefilter(function( options ) {
		options.global = true;
	});
	$("#load").ajaxStart(function(){
		showLoading(); //显示loading
		disableButtons(); //禁用按钮
	});
	$("#load").ajaxComplete(function(){
		hideLoading(); //隐藏loading
		enableButtons(); //启用按钮
	});

});

function showLoading(){
	$("#load").show();
}
function hideLoading(){
	$("#load").hide();
}
function disableButtons(){
	$("#send1").attr("disabled","disabled");
}
function enableButtons(){
	$("#send1").removeAttr("disabled");
}

获取选中的下拉框

<input type="button" id="send1" value="get" onclick="getObj()"/>
<select id="someElement">
	<option>一班</option>
	<option>二班</option>
	<option>三班</option>
</select>

<script>
function getObj(){
	var $obj = $('#someElement').find('option:selected');
	alert( $obj.val() );
}
</script>

切换复选框

<button  >toggle</button>
<input type="checkbox" value="1" />篮球
<input type="checkbox" value="2" />足球
<input type="checkbox" value="3" />羽毛球

<script>
var tog = false; 
$('button').click(function(){
    $("input[type=checkbox]").attr("checked",!tog);
    tog = !tog;
});
</script>

使用siblings()来选择同辈元素

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="../../scripts/jquery.js" type="text/javascript"></script>
<style>
li.active{
	font-size:20px;
	color:red;
}
</style>
</head>
<body>
<ul id="nav">
	<li>Google</li>
	<li>百 度</li>
	<li>新浪</li>
</ul>
<script>
/* 不这样做
$('#nav li').click(function(){
    $('#nav li').removeClass('active');
    $(this).addClass('active');
});
*/
//替代做法是
$('#nav li').click(function(){
    $(this).addClass('active')
           .siblings().removeClass('active');
});

</script>
</body>
</html>

个性化链接

$(document).ready(function(){
	$("a[href$='pdf']").addClass("pdf");
	$("a[href$='zip']").addClass("zip");
    $("a[href$='psd']").addClass("psd");
})

在一段时间之后自动隐藏或关闭元素

$(document).ready(function(){  
	$("button").click(function() {
		$("div").slideUp(300).delay(3000).fadeIn(400);
    });
	/*
	//这是1.3.2中我们使用setTimeout来实现的方式
	setTimeout(function() {
		$('div').fadeIn(400)
	}, 3000);
	*/
	//而在1.4之后的版本可以使用delay()这一功能来实现的方式
	//$("div").slideUp(300).delay(3000).fadeIn(400);
});

使用Firefox和Firebug来记录事件日志

// 在firebug上查看
jQuery.log = jQuery.fn.log = function (msg) {
      if (console){
         console.log("%s: %o", msg, this);
      }
      return this;
};
$(document).ready(function(){  
	$("button").click(function() {
		$('#someDiv').hide().log('div被隐藏');
    });
});

为任何与选择器相匹配的元素绑定事件

$(document).ready(function(){  
	/*
	// 为table里面的td元素绑定click事件,不管td元素是一直存在还是动态创建的
	// jQuery 1.4.2之前使用的方式
	$("table").each(function(){ 
	  $("td", this).live("click", function(){ 
	    $(this).toggleClass("hover"); 
	  }); 
	}); 
	// jQuery 1.4.2 使用的方式
	$("table").delegate("td", "click", function(){ 
	  $(this).toggleClass("hover"); 
	});
	*/
	// jQuery 1.7.1使用的方式
	$("table").on("click","td",function(){ 
	  $(this).toggleClass("hover"); 
	});

});

从元素中除去HTML

(function($) { 
$.fn.stripHtml = function() { 
  var regexp = /<("[^"]*"|'[^']*'|[^'">])*>/gi; 
  this.each(function() { 
    $(this).html( $(this).html().replace(regexp,'') ); 
  });
  return $(this); 
} 
})(jQuery); 
//用法: 
$('div').stripHtml();

扩展String对象的方法

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="../../scripts/jquery.js" type="text/javascript"></script>
</head>
<body>
<div>
<input type="text" /><button >check</button>
</div>
<script>
$.extend(String.prototype, {
isPositiveInteger:function(){
	return (new RegExp(/^[1-9]\d*$/).test(this));
},
isInteger:function(){
	return (new RegExp(/^\d+$/).test(this));
},
isNumber: function(value, element) {
	return (new RegExp(/^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/).test(this));
},
trim:function(){
	return this.replace(/(^\s*)|(\s*$)|\r|\n/g, "");
},
trans:function() {
	return this.replace(/</g, '<').replace(/>/g,'>').replace(/"/g, '"');
},
replaceAll:function(os, ns) {
	return this.replace(new RegExp(os,"gm"),ns);
},
skipChar:function(ch) {
	if (!this || this.length===0) {return '';}
	if (this.charAt(0)===ch) {return this.substring(1).skipChar(ch);}
	return this;
},
isValidPwd:function() {
	return (new RegExp(/^([_]|[a-zA-Z0-9]){6,32}$/).test(this)); 
},
isValidMail:function(){
	return(new RegExp(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/).test(this.trim()));
},
isSpaces:function() {
	for(var i=0; i<this.length; i+=1) {
	var ch = this.charAt(i);
	if (ch!=' '&& ch!="\n" && ch!="\t" && ch!="\r") {return false;}
	}
	return true;
},
isPhone:function() {
	return (new RegExp(/(^([0-9]{3,4}[-])?\d{3,8}(-\d{1,6})?$)|(^\([0-9]{3,4}\)\d{3,8}(\(\d{1,6}\))?$)|(^\d{3,8}$)/).test(this));
},
isUrl:function(){
	return (new RegExp(/^[a-zA-z]+:\/\/([a-zA-Z0-9\-\.]+)([-\w .\/?%&=:]*)$/).test(this));
},
isExternalUrl:function(){
	return this.isUrl() && this.indexOf("://"+document.domain) == -1;
}
});

$("button").click(function(){
	alert(   $("input").val().isInteger()  );
});
</script>
</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: