In this article, we share the jQuery memory leak solution for your reference. The specific content is as follows
Idea: Extend the method of deleting jquery element objects for JQuery, greatly reducing the pressure of memory leaks
;(function($){ if(!$.lui.widget) $.lui.widget = {}; //$.lui.newGuid()生成随机32位id //如果采用此方式多次生成jquery对象的话,html代码字符串会在内存中多次重复,占用额外的内容,也会有泄露。而$("<span></span>").attr('id',_id)写法无此问题。 $.lui.widget.__clean$ = $("<span id='" + $.lui.newGuid()+ "'></span>"); /** * 释放jquery对象,无返回值。此方法用以解决jquery的内存泄露问题 */ $.fn.del = function( selector, keepData ) { if ( !selector || $.filter( selector, [ this ] ).length ) { // 释放dom对象 var item = $(this); var clearItem = $.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} $Element jquery元素 * @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 $Element jquery元素(该元素的字体设置必须已经确定) * @param str 字符串 * @param limit 像素值 * @returns 按像素截取后的字符串 */ $.lui.widget.substrByPx = function($Element,str,limit){ if($Element === undefined || !$Element instanceof $) return ''; if(str === undefined || typeof str != 'string') return ''; if(limit === undefined) return str; if(!str || limit <=0 ) return ''; var _str = new String(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);
The above is the entire content of this article. I hope it will be helpful to everyone's study. I also hope that everyone will support the PHP Chinese website.
For more articles related to jQuery memory leak solutions, please pay attention to the PHP Chinese website!