jQuery技术

javascript之jQuery 性能优化技巧

字号+ 作者:H5之家 来源:H5之家 2017-03-19 18:05 我要评论( )

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

使用最新版本的jQuery类库

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

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

使用合适的选择器 缓存变量

像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=””的超链接将会在新窗口打开链接 $('a[href^="http://"]').attr("target", "_blank"); //例子2:的超链接将会在新窗口打开链接 $("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" value="get"/> <select> <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> <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>

 

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

相关文章
  • jQuery 中的 39 个技巧 码农网

    jQuery 中的 39 个技巧 码农网

    2017-03-20 08:00

  • JQuery实用技巧总结

    JQuery实用技巧总结

    2017-03-19 12:04

  • webjx收集45个jQuery导航插件和教程

    webjx收集45个jQuery导航插件和教程

    2017-03-18 16:00

  • 基于php(Thinkphp)+jquery 实现ajax多选反选不选删除数据功能

    基于php(Thinkphp)+jquery 实现ajax多选反选不选删除数据功能

    2017-03-18 15:03

网友点评
e