search
HomeWeb Front-endJS TutorialJS implements image preloading without waiting

When developing a website, it is often necessary to browse a large number of pictures on a certain page. If you consider traffic, you can only display one picture on each page like pconline, so that users need to re-download the entire picture every time they view it. page. However, in the web2.0 era, more people are willing to use JavaScript to implement an image browser, so that users can see other images without waiting for too long.

After knowing the address of an image, you need to display it in a fixed-size html container (can be a div, etc.). The most important thing is of course to know the width and height of the image to be displayed, and then Combined with the width and height of the container, the image is displayed according to a certain scaling ratio. Therefore, image preloading has become the core function of image browsers.

Friends who have done image flipping effects actually know that in order to avoid waiting when rotating images, it is best to download the images locally and let the browser cache them. At this time, the Image object in js is generally used. The general method is nothing more than this:

Copy the code as follows:

function preLoadImg(url) { 
var img = new Image(); 
img.src = url; 
}


By calling the preLoadImg function and passing in the url of the image, the image can be downloaded in advance. In fact, the pre-download function used here is basically the same. After the image is pre-downloaded, you can know the width and height of the image through the width and height attributes of img. However, you need to consider that when using the image browser function, the images are displayed in real time. For example, when you click the displayed button, the similar code above will be called to load the image. Therefore, if you use img.width directly, the image has not been completely downloaded. Therefore, some asynchronous methods need to be used to wait until the image is downloaded before calling the width and height of img.

It is actually not difficult to implement such an asynchronous method, and the image download completion event is also very simple, it is a simple onload event. Therefore, we can write the following code:

Copy the code The code is as follows:

function loadImage(url, callback) { 
var img = new Image(); 
img.src = url; 
img.onload = function(){ //图片下载完毕时异步调用callback函数。 
callback.call(img); // 将callback函数this指针切换为img。 
}; 
}


Okay, let’s write another test case.

Copy the code as follows:

function imgLoaded(){ 
alert(this.width); 
} 
<input type="button" value="loadImage" onclick="loadImage(&#39;aaa.jpg&#39;,imgLoaded)"/>


Test it in firefox and find that it is good. It is as expected. After the image is downloaded, the width of the image will pop up. No matter how many times you click or refresh the results are the same.

However, when you reach this step, don’t be too happy - you still need to consider the compatibility of the browser, so quickly go to IE to test it. Yes, the width of the image also pops up. However, when I click load again, the situation is different and there is no response. Refresh, same thing.

After testing multiple browser versions, we found that this happens in IE6 and Opera, while Firefox and Safari behave normally. In fact, the reason is quite simple, it is because of the browser's cache. After the image has been loaded once, if there is another request for the image, since the browser has already cached the image, it will not initiate a new request, but load it directly from the cache. For Firefox and Safari, they make these two loading methods transparent to the user, which will also cause the onload event of the image. However, IE and Opera ignore this identity and will not cause the onload event of the image. Therefore, the above code is in No effect can be achieved within them.

What to do? The best case is that the Image can have a status value indicating whether it has been loaded successfully. When loading from the cache, because there is no need to wait, this status value directly indicates that it has been downloaded. When loading from the http request, because it needs to wait for the download, this value is displayed as incomplete. In this case, it can be done.

After some analysis, I finally found an Image attribute that is compatible with various browsers - complete. Therefore, just make a judgment on this value before the image onload event. Finally, the html code becomes as follows:

Copy the code as follows:

function loadImage(url, callback) {
var img = new Image(); //创建一个Image对象,实现图片的预下载
img.src = url;
if (img.complete) { // 如果图片已经存在于浏览器缓存,直接调用回调函数
callback.call(img);
return; // 直接返回,不用再处理onload事件
}
img.onload = function () { //图片下载完毕时异步调用callback函数。
callback.call(img);//将回调函数的this替换为Image对象
};
};

 


After so much trouble, we finally made each browser meet our goals. Although the code is very simple, it solves the core problem of the image browser. All you have to do next is how to present the image. Let’s look at another method:

Copy the code. The code is as follows :

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>js 实现图片预加载 加载完后执行动作</title>
</head>
<style type="text/css">
<!--
*html{
margin:0;
padding:0;
border:0;
}
body{border:1px solid #f3f3f3; background:#fefefe}
div#loading{
width:950px;
height:265px;
line-height:265px;
overflow:hidden;
position:relative;
text-align:center;
}
div#loading p{
position:static;
+position:absolute;
top:50%;
vertical-align:middle;
}
div#loading p img{
position:static;
+position:relative;
top:-50%;left:-50%;
vertical-align:middle
}
-->
</style>
<div id="loading">
<p><img  src="/static/imghwm/default1.png"  data-src="http://www.baidu.com/img/baidu_logo.gif"  class="lazy"   / alt="JS implements image preloading without waiting" ></p>
</div>
<script>
var i=0;
var c=3;
var imgarr=new Array
imgarr[0]="http://www.baidu.com/img/baidu_logo.gif";
imgarr[1]="http://img.baidu.com/img/logo-img.gif";
imgarr[2]="http://img.baidu.com/img/logo-zhidao.gif";
var Browser=new Object();
Browser.userAgent=window.navigator.userAgent.toLowerCase();
Browser.ie=/msie/.test(Browser.userAgent);
Browser.Moz=/gecko/.test(Browser.userAgent);
function SImage(url,callback)
{
var img = new Image();
if(Browser.ie){
img.onreadystatechange =function(){
if(img.readyState=="complete"||img.readyState=="loaded"){
ii=i+1;
callback(i);
}
}
}else if(Browser.Moz){
img.onload=function(){
if(img.complete==true){
ii=i+1;
callback(i);
}
}
}
img.src=url;
}
function icall(v)
{
if(v<c){
SImage(""+imgarr[v]+"",icall);
}
else if(v>=c){
i=0;
//location.replace(&#39;banner.html&#39;);//这里写自己的动作吧,
}
}

 


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

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.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

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 the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

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 vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

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 vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

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.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

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.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

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.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

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.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment