


How to implement image preloading and delayed loading with Jquery_jquery
The example in this article describes how Jquery implements image preloading and delayed loading. Share it with everyone for your reference. The specific analysis is as follows:
There are many projects that often need to determine whether to perform corresponding operations after the image is loaded, or to delay loading of the image. Although there are already very good plug-ins on the Internet, it always feels a bit awkward to have to load a separate plug-in for these effects. It’s so comfortable, I just wrote a method myself:
var numLoaded=0,
numError=0,
isObject=Object.prototype.toString.call(arr)==="[object Object]" ? true : false;
var arr=isObject ? arr.get() : arr;
for(a in arr){
var src=isObject ? $(arr[a]).attr("data-src") : arr[a];
preload(src,arr[a]);
}
function preload(src,obj){
var img=new Image();
img.onload=function(){
numLoaded ;
funLoading && funLoading(numLoaded,arr.length,src,obj);
funOnLoad && numLoaded==arr.length && funOnLoad(numError);
};
img.onerror=function(){
numLoaded ;
numError ;
funOnError && funOnError(numLoaded,arr.length,src,obj);
}
img.src=src;
}
}
Parameter description:
arr: It can be an array to store the image path, or it can be the jquery object of the selected img;
funLoading: The operation performed after each individual image is loaded;
funOnLoad: Operation after all images are loaded;
funOnError: Operation when a single image loading error occurs.
For example:
/*errors: Number of pictures with loading errors;*/
console.log("loaded," errors " images loaded error!");
}
var funloading=function(n,total,src,obj){
/*
n: The number of loaded items;
total: the total number of images to be loaded;
SRC: The picture path that is currently loaded;
obj: When the arr passed in the loadimg function is an array storing the image path, obj=src is the image path,
When arr is a jquery object, obj is the currently loaded img dom object.
*/
console.log(n "of" total " pic loaded.",src);
var newimg = document.createElement("img");
newimg.src=src;
$("body").append(newimg).fadeIn();
}
var funloading_obj=function(n,total,src,obj){
console.log(n "of" total " pic loaded.",src);
$(obj).attr("src",src);
$(obj).fadeIn(200);
}
var funOnError=function(n,total,src,obj){
console.log("the " n "st img loaded Error!");
}
Call example:
loadimg($("img"),funloading_obj,imgonload,funOnError);
/*loadimg(["http://pic22.nipic.com/20120619/9607634_212642465144_2.jpg",
"/20120531/1670912_103610084349_2.jpg",
"/20120616/4952071_130629530136_2.jpg",
"/20120610/1723580_105037029000_2.jpg",
"http://pic22.nipic.com/20120617/2572038_125013326121_2.jpg"
],funloading,imgonload,funOnError);*/
The above is the original writing method. Next we introduce a jQuery plug-in for lazy loading of images based on Lazy Load
Lazy Load depends on jQuery. Please add the following code to the head area of the page:
You must modify the HTML code. Set the booth symbol image in the src attribute. The demo page uses a 1x1 pixel gray GIF image. And you need to set the URL of the real image to the data-original attribute. Here you can define a specific class to obtain the lazy loading Image object. This way you can simply control plugin bindings.

The code for processing images is as follows.
This will cause all images with class lazy to be loaded lazily. You can refer to the basic options demo
Set sensitivity
JavaScript is enabled in almost all browsers. However, you may still want to display real images on clients that do not support JavaScript. To degrade gracefully when the browser does not support JavaScript, you can write real image fragments

Placeholders can be hidden via CSS.
display: none;
}
In browsers that support JavaScript, you must display the placeholder when the DOM is ready, which can be done at the same time as the plugin is initialized.
These are optional, but should be done if you want your plugin to downgrade gracefully.
Set sensitivity
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 threshold to 200 to make the image load in advance when it is 200 pixels away from the screen.
Placeholder image
You can also set a placeholder image and define events to trigger the loading action. At this time, you need to set a URL address for the placeholder image. Transparent, gray and white 1x1 pixel images are already included in the plug-in.
Event triggered 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 position of the picture on the window. In gray To prevent the placeholder image from loading until it is clicked, you can do this:
placeholder: "img/grey.gif",
event : "click"
});
Use special effects
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. The following code uses the FadeIn effect. This is the effect demonstration page.
Effect: "fadeIn"
});
The image is inside the container
You can use the plug-in on images in scrollable containers, such as DIV elements with scroll bars. All you have to do is define the container as a jQuery object and pass it as a parameter to the initialization method. This is a horizontal scrolling demo page and vertical scrolling demo page.
Height: 600px;
Overflow: scroll;
}
$("img.lazy").lazyload({
container: $("#container")
});
When the pictures are not arranged in order
When scrolling the page, Lazy Load will loop through the loaded images. In the loop, it will detect whether the image is within the visible area. By default, the loop will stop when the first image that is not in the visible area is found. The image is considered Fluidly distributed, the order of the images in the page is the same as the order in the HTML code. But in some layouts, this assumption is not true. However, you can control the loading behavior through the failurelimit option.
Failure_limit : 10
});
Set the failurelimit to 10 so that the plugin stops searching after finding 10 images that are not in the visible area. If you have a cumbersome layout, please set this parameter higher.
Lazy loading of images
An incomplete function of the Lazy Load plug-in, but it can also be used to implement lazy loading of images. The following code implements loading after the page is loaded. 5 seconds after the page is loaded, the images in the specified area will Load automatically. This is the lazy loading demo page.
$("img:below-the-fold").lazyload({
event: "sporty"
});
});
$(window).bind("load", function() {
var timeout = setTimeout(function() {$("img.lazy").trigger("sporty")}, 5000);
});
Loading hidden images
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 status of each item in the list. In order to improve performance, Lazy Load ignores hidden pictures by default. If you want to load hidden images, please set skip_invisible to false
Skip_invisible : false
});
I hope this article will be helpful to everyone’s JavaScript programming design.

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

Hot Topics



Tomato Novel is a very popular novel reading software. We often have new novels and comics to read in Tomato Novel. Every novel and comic is very interesting. Many friends also want to write novels. Earn pocket money and edit the content of the novel you want to write into text. So how do we write the novel in it? My friends don’t know, so let’s go to this site together. Let’s take some time to look at an introduction to how to write a novel. Share the Tomato novel tutorial on how to write a novel. 1. First open the Tomato free novel app on your mobile phone and click on Personal Center - Writer Center. 2. Jump to the Tomato Writer Assistant page - click on Create a new book at the end of the novel.

With the continuous development of social media, Xiaohongshu has become a platform for more and more young people to share their lives and discover beautiful things. Many users are troubled by auto-save issues when posting images. So, how to solve this problem? 1. How to solve the problem of automatically saving pictures when publishing on Xiaohongshu? 1. Clear the cache First, we can try to clear the cache data of Xiaohongshu. The steps are as follows: (1) Open Xiaohongshu and click the "My" button in the lower right corner; (2) On the personal center page, find "Settings" and click it; (3) Scroll down and find the "Clear Cache" option. Click OK. After clearing the cache, re-enter Xiaohongshu and try to post pictures to see if the automatic saving problem is solved. 2. Update the Xiaohongshu version to ensure that your Xiaohongshu

Unfortunately, people often delete certain contacts accidentally for some reasons. WeChat is a widely used social software. To help users solve this problem, this article will introduce how to retrieve deleted contacts in a simple way. 1. Understand the WeChat contact deletion mechanism. This provides us with the possibility to retrieve deleted contacts. The contact deletion mechanism in WeChat removes them from the address book, but does not delete them completely. 2. Use WeChat’s built-in “Contact Book Recovery” function. WeChat provides “Contact Book Recovery” to save time and energy. Users can quickly retrieve previously deleted contacts through this function. 3. Enter the WeChat settings page and click the lower right corner, open the WeChat application "Me" and click the settings icon in the upper right corner to enter the settings page.

With the popularity of Douyin short videos, user interactions in the comment area have become more colorful. Some users wish to share images in comments to better express their opinions or emotions. So, how to post pictures in TikTok comments? This article will answer this question in detail and provide you with some related tips and precautions. 1. How to post pictures in Douyin comments? 1. Open Douyin: First, you need to open Douyin APP and log in to your account. 2. Find the comment area: When browsing or posting a short video, find the place where you want to comment and click the "Comment" button. 3. Enter your comment content: Enter your comment content in the comment area. 4. Choose to send a picture: In the interface for entering comment content, you will see a "picture" button or a "+" button, click

In PowerPoint, it is a common technique to display pictures one by one, which can be achieved by setting animation effects. This guide details the steps to implement this technique, including basic setup, image insertion, adding animation, and adjusting animation order and timing. Additionally, advanced settings and adjustments are provided, such as using triggers, adjusting animation speed and order, and previewing animation effects. By following these steps and tips, users can easily set up pictures to appear one after another in PowerPoint, thereby enhancing the visual impact of the presentation and grabbing the attention of the audience.

Some netizens found that when they opened the browser web page, the pictures on the web page could not be loaded for a long time. What happened? I checked that the network is normal, so where is the problem? The editor below will introduce to you six solutions to the problem that web page images cannot be loaded. Web page images cannot be loaded: 1. Internet speed problem The web page cannot display images. It may be because the computer's Internet speed is relatively slow and there are more softwares opened on the computer. And the images we access are relatively large, which may be due to loading timeout. As a result, the picture cannot be displayed. You can turn off the software that consumes more network speed. You can go to the task manager to check. 2. Too many visitors. If the webpage cannot display pictures, it may be because the webpages we visited were visited at the same time.

Setting font size has become an important personalization requirement as mobile phones become an important tool in people's daily lives. In order to meet the needs of different users, this article will introduce how to improve the mobile phone use experience and adjust the font size of the mobile phone through simple operations. Why do you need to adjust the font size of your mobile phone - Adjusting the font size can make the text clearer and easier to read - Suitable for the reading needs of users of different ages - Convenient for users with poor vision to use the font size setting function of the mobile phone system - How to enter the system settings interface - In Find and enter the "Display" option in the settings interface - find the "Font Size" option and adjust it. Adjust the font size with a third-party application - download and install an application that supports font size adjustment - open the application and enter the relevant settings interface - according to the individual

When using WPS office software, we found that not only one form is used, tables and pictures can be added to the text, pictures can also be added to the table, etc. These are all used together to make the content of the entire document look richer. , if you need to insert two pictures into the document and they need to be arranged side by side. Our next course can solve this problem: how to place two pictures side by side in a wps document. 1. First, you need to open the WPS software and find the picture you want to adjust. Left-click the picture and a menu bar will pop up, select "Page Layout". 2. Select "Tight wrapping" in text wrapping. 3. After all the pictures you need are confirmed to be set to "Tight text wrapping", you can drag the pictures to the appropriate position and click on the first picture.
