Home > Web Front-end > JS Tutorial > body text

JS implements image preloading without waiting

高洛峰
Release: 2016-11-05 16:45:33
Original
1225 people have browsed it

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; 
}
Copy after login


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。 
}; 
}
Copy after login


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)"/>
Copy after login


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对象
};
};
Copy after login

 


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="http://www.baidu.com/img/baidu_logo.gif" / 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;);//这里写自己的动作吧,
}
}
Copy after login

 


Related labels:
js
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!