优化 jQuery 插件的性能,核心思路是减少 DOM 操作、减少重排重绘、缓存结果、避免重复绑定、按需执行。下面从常见痛点出发,给你一套实用优化清单。
$(this).find('.item').addClass('active');
$(this).find('.item').removeClass('hide');
var $items = $(this).find('.item');
$items.addClass('active').removeClass('hide');
✅ 原则:
$('.list li').on('click', function () {});
$('.list').on('click', 'li', function () {});
✅ 好处:
$.each(data, function (i, item) {
$('#box').append('<div>' + item + '</div>');
});
var html = '';
$.each(data, function (i, item) {
html += '<div>' + item + '</div>';
});
$('#box').append(html);
✅ 或一次性 html() / append()
this 和 $this$.fn.myPlugin = function () {
return this.each(function () {
var $this = $(this);
// 使用 $this
});
};
(function ($) {
var defaults = {
speed: 300
};
function Plugin(element, options) {
this.$el = $(element);
this.settings = $.extend({}, defaults, options);
this.init();
}
Plugin.prototype.init = function () {
// 初始化
};
$.fn.myPlugin = function (options) {
return this.each(function () {
if (!$.data(this, 'myPlugin')) {
$.data(this, 'myPlugin', new Plugin(this, options));
}
});
};
})(jQuery);
✅ 优点:
$.data 保存实例resizescrollmousemovefunction throttle(fn, delay) {
var timer = null;
return function () {
if (!timer) {
fn.apply(this, arguments);
timer = setTimeout(() => timer = null, delay);
}
};
}
// 慢
$(el).css('display', 'none');
// 快
el.style.display = 'none';
✅ 在循环或高频操作中尤其有效
$(window).on('scroll', function () {
if (inView($el)) {
$el.myPlugin();
}
});
transform / opacityrequestAnimationFrameconsole.time() 测耗时jQuery 插件性能优化 = 少查 DOM + 少绑事件 + 缓存对象 + 批量操作 + 原生加速
如果你有具体插件代码,我可以直接帮你逐行优化。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。