在 jQuery 生态里,“插件做懒加载”通常有两种理解,下面分别说明,并给出常见、实用的做法。
(页面一开始不加载插件,等用到时再加载)
function loadJQueryPlugin(cb) {
if (window.MyPluginLoaded) {
cb();
return;
}
$.getScript('jquery.myplugin.js').done(function () {
window.MyPluginLoaded = true;
cb();
});
}
// 使用
$('#btn').on('click', function () {
loadJQueryPlugin(function () {
$('#box').myPlugin();
});
});
✅ 适合:
const io = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
$.getScript('jquery.lazy.plugin.js').done(() => {
$(entry.target).lazyPlugin();
});
io.unobserve(entry.target);
}
});
});
$('.lazy-plugin').each(function () {
io.observe(this);
});
✅ 适合:
(插件本身不立即执行,等元素进入视口再执行)
(function ($) {
$.fn.lazyInit = function (options) {
const settings = $.extend({
init: function () {}
}, options);
const io = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
settings.init.call($(entry.target));
io.unobserve(entry.target);
}
});
});
return this.each(function () {
io.observe(this);
});
};
})(jQuery);
$('.box').lazyInit({
init: function () {
this.html('已懒加载');
}
});
如果你只是想“jQuery 做图片懒加载”:
<img class="lazy" data-src="a.jpg">
$('img.lazy').each(function () {
const img = this;
const io = new IntersectionObserver((entries) => {
if (entries[0].isIntersecting) {
img.src = img.dataset.src;
io.disconnect();
}
});
io.observe(img);
});
✅ 优先用 IntersectionObserver(性能好)
✅ jQuery 只负责 DOM 操作
✅ 插件脚本能懒加载就懒加载
✅ 避免页面初始化时全量加载插件
如果你能说一下:
我可以直接给你一份可复制的完整示例。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。