Home >Web Front-end >JS Tutorial >A way to lazily load images with jquery
This article mainly introduces jquery to implement asynchronous loading (a method of lazy loading of images), which has certain reference value. Interested friends can refer to it.
First introduce the plug-in behind 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);
Then initialize it at the bottom
$(document).ready(function () { //实现图片慢慢浮现出来的效果 $("img").load(function () { //图片默认隐藏 $(this).hide(); //使用fadeIn特效 $(this).fadeIn("5000"); }); // 异步加载图片,实现逐屏加载图片 $(".scrollLoading").scrollLoading(); });
You need to modify the img tag to
<img class="scrollLoading" data-url="image/logo.jpg" src="images/load.gif" />
data-url indicates the image to be loaded asynchronously, and src indicates the image to be loaded first (usually a small Picture, or an animation, all src in the web page link to the same picture, so that the web page loads much faster. At this time, the picture to be loaded is loaded asynchronously, which is the function I want to talk about now)
Related recommendations:
Detailed explanation of image lazy loading imgLazyLoading.js
Steps to implement lazy loading and cross-domain implementation using Js
Introduction to the lazy loading method of images using JavaScript
The above is the detailed content of A way to lazily load images with jquery. For more information, please follow other related articles on the PHP Chinese website!