jquery实现异步加载图片(懒加载图片一种方式)
首先将插件在jq后面引入
(function($) { // alert($.fn.scrollLoading); $.fn.scrollLoading = function(options) { var defaults = { attr: "data-url" }; var params = $.extend({}, defaults, options || {}); params.cache = []; $(this).each(function() { var node = this.nodeName.toLowerCase(), url = $(this).attr(params["attr"]); if(!url) { return; } var data = { obj: $(this), tag: node, url: url }; params.cache.push(data); }); var loading = function() { var st = $(window).scrollTop(), sth = st + $(window).height(); $.each(params.cache, function(i, data) { var o = data.obj, tag = data.tag, url = data.url; if(o) { post = o.position().top; posb = post + o.height(); if((post > st && post < sth) || (posb > st && posb < sth)) { if(tag === "img") { o.attr("src", url); } else { o.load(url); } data.obj = null; } } }); return false; }; loading(); $(window).bind("scroll", loading); }; })(jQuery);
然后在底部初始化
$(document).ready(function () { //实现图片慢慢浮现出来的效果 $("img").load(function () { //图片默认隐藏 $(this).hide(); //使用fadeIn特效 $(this).fadeIn("5000"); }); // 异步加载图片,实现逐屏加载图片 $(".scrollLoading").scrollLoading(); });
需要修改img标签为
<img class="scrollLoading" data-url="image/logo.jpg" src="images/load.gif" />
data-url表示将要异步加载的图片,src表示首先加载的图片(一般会是小图片,或者是一个动画,网页中全部的src链接同一个图片,这样网页就加载快好多,这个时候再异步的加载要加载的图片,也就现在要说的功能)
相关推荐
ppsurcao 2020-06-14
86193952 2020-10-27
小木兮子 2020-11-11
HeyShHeyou 2020-11-17
seanzed 2020-10-15
huangliuyu00 2020-09-24
libaoshan 2020-09-11
zhangpan 2020-09-10
chongxiaocheng 2020-08-16
xcguoyu 2020-08-15
Qizonghui 2020-08-02
ldcwang 2020-07-26
mqfcu 2020-07-21
jeason 2020-07-20
sunzhihaofuture 2020-07-19
knightwatch 2020-07-19
点滴技术生活 2020-07-19
Reiki 2020-07-06