Lazy loading of images and usage examples of jquery.lazyload.js
Sometimes lazy loading of images is used in projects, so what are the benefits of lazy loading?
I think it mainly includes two points. The first is that delaying the loading of images in long pages that contain many large images can speed up page loading; the second is to help reduce the load on the server.
The following introduces the commonly used lazy loading plug-in jquery.lazyload.js and how to implement a lazy loading plug-in.
1: jquery.lazyload.js plug-in
lazyload is a lazy loading plug-in written by jQuery. Images outside the visible area of the browser will not be loaded until the user scrolls the page to Where they are. This is the exact opposite of how image preloading is handled.
Implementation Principle
Firstly, the selected img element is bound to an appear event (processing the img to display the real image address), so that the event can be triggered when the conditions are met in the future;
There is a container attribute configuration in the configuration object. The default is window. If the img element is in the container container viewport, the appear event is triggered;
In order to determine whether the img element is in the container container viewport range, there is The following four methods:
$.belowthefold = function(element, settings) {}; // 在视口下方$.rightoffold = function(element, settings) {}; // 在视口右方$.abovethetop = function(element, settings) {}; // 在视口上方$.leftofbegin = function(element, settings) {}; // 在视口左方
Specific use
1. Page introduction method
Since lazyload relies on jquery, all pages need to be introduced jquery, as follows:
<script></script><script></script>
Basic writing method:
<img alt="Lazy loading of images and usage examples of jquery.lazyload.js" >$(function() { $("img.lazy").lazyload(); });
The data-original attribute stores the real image url path.
Tips: You must set the width or height of the image in css, otherwise the plugin may not work properly.
Set Threshold
By default, the image will be loaded when it appears on the screen. If you want to load the image in advance, you can set the threshold option. Set the threshold to 200 so that the image is 200 from the screen. Pixels are loaded ahead of time.
$("img.lazy").lazyload({ threshold : 200});
Set events to trigger loading
The event can be any jQuery event, such as: click and mouseover. You can also use custom events, such as: sporty and foobar . By default, it is in a waiting state until the user scrolls to the location of the image on the window. To prevent the image from loading until the gray placeholder image is clicked, you can do this:
$("img.lazy").lazyload({ event : "click"});
Of course, You can also use the following method to implement lazy loading:
$(function() { $("img.lazy").lazyload({ event : "sporty"}); }); $(window).bind("load", function() {var timeout = setTimeout(function() { $("img.lazy").trigger("sporty") }, 5000); });
That is, 5 seconds after the page is loaded, perform lazy loading of the image.
Lazy loading effect
When the image is fully loaded, the plug-in uses the show() method by default to display the image. In fact, you can use any special effects you want to process. Below The code uses FadeIn Effect:
$("img.lazy").lazyload({ effect : "fadeIn"});
How to use browsers that do not support JavaScript
JavaScript is activated in almost all browsers. However, you may still want to Able to display real images on clients that do not support JavaScript. For graceful degradation when the browser does not support JavaScript, you can write real image fragments in the
<img alt="Lazy loading of images and usage examples of jquery.lazyload.js" ><noscript><img alt="Lazy loading of images and usage examples of jquery.lazyload.js" ></noscript>
You can hide the placeholder through CSS:
.lazy { display: none; }
In browsers that support JavaScript, you must add the placeholder when the DOM is ready The bitmap is displayed, this can be done at the same time as the plugin is initialized.
$("img.lazy").show().lazyload();
Set up a lazy-loaded image container
You can use the plug-in on images in scrollable containers, such as DIV elements with scroll bars. What you have to do Just define the container as a jQuery object and pass it as a parameter to the initialization method:
#container { height: 600px; overflow: scroll; } $("img.lazy").lazyload({ container: $("#container") });
When the pictures are not arranged in order
When the page is scrolled, Lazy Load will loop as Loaded images. Check in the loop whether the image is within the visible area. By default the loop stops when it finds the first image that is not in the visible area. Images are considered to be distributed in a streaming manner, and the order of the images in the page and the HTML The order in the code is the same. But in some layouts, this assumption is not true. However, you can control the loading behavior through the failurelimit option.
$("img.lazy").lazyload({ failure_limit : 10});
Set the failurelimit to 10 so that the plug-in will stop searching after finding 10 images that are not in the visible area. If you have a cumbersome layout, please set this parameter higher.
Set up to load hidden pictures
There may be many hidden pictures buried on your page. For example, if the plug-in is used to filter the list, you can continuously modify the display of each item in the list. Status. To improve performance, Lazy Load ignores hidden images by default. If you want to load hidden images, set skip_invisible to false.
$("img.lazy").lazyload({ skip_invisible : true});
Source code
Official website address:
/*! * Lazy Load - jQuery plugin for lazy loading images * * Copyright (c) 2007-2015 Mika Tuupola * * Licensed under the MIT license: * * * Project home: * * * Version: 1.9.7 * */ (function($, window, document, undefined) {var $window = $(window); $.fn.lazyload = function(options) {var elements = this;var $container;var settings = { threshold : 0, failure_limit : 0, event : "scroll", effect : "show", container : window, data_attribute : "original", skip_invisible : false, appear : null, load : null, placeholder : "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXYzh8+PB/AAffA0nNPuCLAAAAAElFTkSuQmCC"}; function update() {var counter = 0; elements.each(function() {var $this = $(this);if (settings.skip_invisible && !$this.is(":visible")) {return; }if ($.abovethetop(this, settings) ||$.leftofbegin(this, settings)) {/* Nothing. */} else if (!$.belowthefold(this, settings) && !$.rightoffold(this, settings)) { $this.trigger("appear");/* if we found an image we'll load, reset the counter */counter = 0; } else {if (++counter > settings.failure_limit) {return false; } } }); } if(options) {/* Maintain BC for a couple of versions. */if (undefined !== options.failurelimit) { options.failure_limit = options.failurelimit;delete options.failurelimit; }if (undefined !== options.effectspeed) { options.effect_speed = options.effectspeed;delete options.effectspeed; } $.extend(settings, options); } /* Cache container as jQuery as object. */$container = (settings.container === undefined || settings.container === window) ? $window : $(settings.container); /* Fire one scroll event per scroll. Not one scroll event per image. */if (0 === settings.event.indexOf("scroll")) { $container.bind(settings.event, function() {return update(); }); } this.each(function() {var self = this;var $self = $(self); self.loaded = false; /* If no src attribute given use data:uri. */if ($self.attr("src") === undefined || $self.attr("src") === false) {if ($self.is("img")) { $self.attr("src", settings.placeholder); } } /* When appear is triggered load original image. */$self.one("appear", function() {if (!this.loaded) {if (settings.appear) {var elements_left = elements.length; settings.appear.call(self, elements_left, settings); } $("<img src="/static/imghwm/default1.png" data-src="images/loading.gif" class="lazy" alt="Lazy loading of images and usage examples of jquery.lazyload.js" >") .bind("load", function() { var original = $self.attr("data-" + settings.data_attribute); $self.hide();if ($self.is("img")) { $self.attr("src", original); } else { $self.css("background-image", "url('" + original + "')"); } $self[settings.effect](settings.effect_speed); self.loaded = true; /* Remove image from array so it is not looped next time. */var temp = $.grep(elements, function(element) {return !element.loaded; }); elements = $(temp); if (settings.load) {var elements_left = elements.length; settings.load.call(self, elements_left, settings); } }) .attr("src", $self.attr("data-" + settings.data_attribute)); } }); /* When wanted event is triggered load original image *//* by triggering appear. */if (0 !== settings.event.indexOf("scroll")) { $self.bind(settings.event, function() {if (!self.loaded) { $self.trigger("appear"); } }); } }); /* Check if something appears when window is resized. */$window.bind("resize", function() { update(); }); /* With IOS5 force loading images when navigating with back button. *//* Non optimal workaround. */if ((/(?:iphone|ipod|ipad).*os 5/gi).test(navigator.appVersion)) { $window.bind("pageshow", function(event) {if (event.originalEvent && event.originalEvent.persisted) { elements.each(function() { $(this).trigger("appear"); }); } }); } /* Force initial check if images should appear. */$(document).ready(function() { update(); }); return this; }; /* Convenience methods in jQuery namespace. *//* Use as $.belowthefold(element, {threshold : 100, container : window}) */ $.belowthefold = function(element, settings) {var fold; if (settings.container === undefined || settings.container === window) { fold = (window.innerHeight ? window.innerHeight : $window.height()) + $window.scrollTop(); } else { fold = $(settings.container).offset().top + $(settings.container).height(); } return fold = $(element).offset().top + settings.threshold + $(element).height(); }; $.leftofbegin = function(element, settings) {var fold; if (settings.container === undefined || settings.container === window) { fold = $window.scrollLeft(); } else { fold = $(settings.container).offset().left; } return fold >= $(element).offset().left + settings.threshold + $(element).width(); }; $.inviewport = function(element, settings) { return !$.rightoffold(element, settings) && !$.leftofbegin(element, settings) && !$.belowthefold(element, settings) && !$.abovethetop(element, settings); }; /* Custom selectors for your convenience. *//* Use as $("img:below-the-fold").something() or *//* $("img").filter(":below-the-fold").something() which is faster */ $.extend($.expr[":"], {"below-the-fold" : function(a) { return $.belowthefold(a, {threshold : 0}); },"above-the-top" : function(a) { return !$.belowthefold(a, {threshold : 0}); },"right-of-screen": function(a) { return $.rightoffold(a, {threshold : 0}); },"left-of-screen" : function(a) { return !$.rightoffold(a, {threshold : 0}); },"in-viewport" : function(a) { return $.inviewport(a, {threshold : 0}); },/* Maintain BC for couple of versions. */"above-the-fold" : function(a) { return !$.belowthefold(a, {threshold : 0}); },"right-of-fold" : function(a) { return $.rightoffold(a, {threshold : 0}); },"left-of-fold" : function(a) { return !$.rightoffold(a, {threshold : 0}); } }); })(jQuery, window, document);
2: Handwrite a simple lazy loading plug-in
js code
window.smallDelay = (function(window, document, undefined) {'use strict';var store = [],poll;var settings = { offset:0, //离可视区域多少像素的图片可以被加载throttle: 250 //图片延时多少毫秒加载 } var _inView = function(el) {var coords = el.getBoundingClientRect();return ((coords.top >= 0 && coords.left >= 0) && coords.top
Calling method:
smallDelay.init({ offset: 0,//离可视区域多少像素的图片可以被加载 throttle: 0 //图片延时多少毫秒加载});
html code:
<img src="/static/imghwm/default1.png" data-src="images/loading.gif" class="lazy" alt="Lazy loading of images and usage examples of jquery.lazyload.js" >
三:根据lazyload插件实现一个不依赖jQuery的懒加载插件
实现内容
1、增加了图片预加载可选
2、修改了图片本身就在可视范围的时候直接显示而不需要滚动条触发
3、修改了Splice删除数组的时候,会跳过下一张图片BUG
4、浏览器窗口resize的时候图片出现也会加载
5、判断图片父层包裹顶部或者底部出现在可视范围内即可显示图片
实现源码
var Lazy = { $:function(arg,context){var tagAll,n,eles=[],i,sub = arg.substring(1); context = context|| document;if(typeof arg =='string'){switch(arg.charAt(0)){case '#':return document.getElementById(sub);break;case '.':if(context.getElementsByClassName) return context.getElementsByClassName(sub); tagAll = Lazy.$('*'); n = tagAll.length;for(i = 0;i<n> -1) eles.push(tagAll[i]); }return eles;break;default:return context.getElementsByTagName(arg);break; } } }, getPos:function (node) {var scrollx = document.documentElement.scrollLeft || document.body.scrollLeft, scrollt = document.documentElement.scrollTop || document.body.scrollTop;var pos = node.getBoundingClientRect();return {top:pos.top + scrollt, right:pos.right + scrollx, bottom:pos.bottom + scrollt, left:pos.left + scrollx } }, bind:function(node,type,handler){ node.addEventListener?node.addEventListener(type, handler, false):node.attachEvent('on'+ type, handler); }, unbind:function(node,type,handler){ node.removeEventListener?node.removeEventListener(type, handler, false):node.detachEvent('on'+ type, handler); }, toArray:function(eles){var arr = [];for(var i=0,n=eles.length;i<n> scrollTop && posT scrollTop && posB </n></n>
使用方法
1、在图片上增加lazyload的类(class='lazyload')
2、把真实的图片地址放入自定义属性data-img 中,把图片的SRC属性设置为一个一像素的透明图片,图片需要设置width,height属性,以免布局混乱
如下:
<img src="/static/imghwm/default1.png" data-src="loading.gif" class="lazy" alt="Lazy loading of images and usage examples of jquery.lazyload.js" >
3、在需要延迟加载的页面调用imgLazyLoad()函数;
该原生js实现的懒加载转载地址:
The above is the detailed content of Lazy loading of images and usage examples of jquery.lazyload.js. For more information, please follow other related articles on the PHP Chinese website!

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

Dreamweaver Mac version
Visual web development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Mac version
God-level code editing software (SublimeText3)