jQuery内存泄露解决办法
本文大家分享了jQuery内存泄露解决办法,供大家参考,具体内容如下
思路:为JQuery扩展删除jquery元素对象的方法,大大减轻内存泄露的压力
;(function($){
if(!$.lui.widget)$.lui.widget={};
//$.lui.newGuid()生成随机32位id
//如果采用此方式多次生成jquery对象的话,html代码字符串会在内存中多次重复,占用额外的内容,也会有泄露。而$("<span></span>").attr('id',_id)写法无此问题。
$.lui.widget.__clean$=$("<spanid='"+$.lui.newGuid()+"'></span>");
/**
*释放jquery对象,无返回值。此方法用以解决jquery的内存泄露问题
*/
$.fn.del=function(selector,keepData){
if(!selector||$.filter(selector,[this]).length){
//释放dom对象
varitem=$(this);
varclearItem=$.lui.widget.__clean$;
item.appendTo(clearItem);
$('*',clearItem).each(function(i,e){
(events=$.data(this,'events'))&&$.each(events,function(i,e1){
$(e).unbind(i+'.*');
});
$.event.remove(this);
$.removeData(this);
});
clearItem[0].innerHTML='';
item=null;
}
};
/**
*计算字符串在某元素上不折行时的长度
*@param{jQuery}$Elementjquery元素
*@param{String}str字符串
*@returns{Number}字符串长度(px)
*/
$.lui.widget.clacStrLength=function($Element,str){
var_id=$.lui.newGuid();
var$tmpSpan=$("<span></span>").attr('id',_id).css({
'position':'absolute',
'top':'-1000px'
}).appendTo('body');
var_width=$tmpSpan.css({
'font-family':$Element.css('font-family'),
'font-size':$Element.css('font-size'),
'letter-spacing':$Element.css('letter-spacing'),
'word-spacing':$Element.css('word-spacing'),
'text-indent':$Element.css('text-indent')
}).text(str).innerWidth();
$tmpSpan.del();
$tmpSpan=null;
return_width;
};
/**
*在某元素上按像素截取字符串(采用浏览器默认处理空白方式,不适用于复杂场景,仅用于不换行情况下按像素截取字符串)
*@param$Elementjquery元素(该元素的字体设置必须已经确定)
*@paramstr字符串
*@paramlimit像素值
*@returns按像素截取后的字符串
*/
$.lui.widget.substrByPx=function($Element,str,limit){
if($Element===undefined||!$Elementinstanceof$)return'';
if(str===undefined||typeofstr!='string')return'';
if(limit===undefined)returnstr;
if(!str||limit<=0)return'';
var_str=newString(str);
var_id=$.lui.newGuid();
var$tmpSpan=$("<span></span>").attr('id',_id).css({
'position':'absolute',
'top':'-1000px'
}).appendTo('body');
var_width=$tmpSpan.css({
'font-family':$Element.css('font-family'),
'font-size':$Element.css('font-size'),
'letter-spacing':$Element.css('letter-spacing'),
'word-spacing':$Element.css('word-spacing'),
'text-indent':$Element.css('text-indent')
}).text(str).innerWidth();
while(_width>limit){
_str=_str.substring(0,_str.length-1);
_width=$tmp.text(_str).innerWidth();
}
$tmpSpan.del();
$tmpSpan=null;
return_str;
};
})(jQuery);
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。