JS implementation picture pre-loading without waiting

Source: Internet
Author: User
Tags browser cache

JS implementation picture preloaded without waiting for http://www.jb51.net/article/32761.htm

Web site development often need to implement a large number of images on a page, if you consider traffic, large can be like pconline, each page only display a picture, so that the user every look at a picture will need to re-download the entire page. However, in the web2.0 era, more people are willing to use JavaScript to implement a picture browser, so that users do not have to wait a long time to see other pictures.

Know the address of a picture, you need to put it in a fixed-size HTML container (can be div, etc.) inside the display, the most important of course is to know the picture is about to show the width and height, and then combined with the width and height of the container, according to a certain scale to make the picture display. Therefore, the implementation of the picture pre-loading becomes the core function of the picture browser.

Do the picture flipping effect of friends actually know, want to let the picture rotation time does not appear waits, the best is to let the picture download to local, let the browser cache up. At this time, the general will use JS inside the image object. The general means is nothing more than this:

Copy CodeThe code is 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 pre-downloaded. In fact, the pre-download functionality used here is basically consistent with this. After the image is pre-downloaded, the width and height properties of the IMG will tell you the width and height of the image. But take into account, in the Image browser function, the picture is displayed in real time. For example, if you click on the button to display, this time it will invoke similar code above to load the image. Therefore, if you use Img.width directly, the picture is not fully downloaded. Therefore, it is necessary to use some asynchronous methods to wait until the picture is downloaded, and then the width and height of the IMG will be called.

The implementation of such an asynchronous method is not really difficult, the download of the picture is also very simple event is simple onload event. Therefore, we can write the following code:

Copy CodeThe code is as follows:
function LoadImage (URL, callback) {
var img = new Image ();
img.src = URL;
Img.onload = function () {/////The picture is downloaded asynchronously when callback functions are called.
Callback.call (IMG); Switch the callback function this pointer to IMG.
};
}


Well, then write a test case.

Copy CodeThe code is as follows:
function imgloaded () {
alert (this.width);
}
<input type= "button" value= "LoadImage" onclick= "LoadImage (' aaa.jpg ', imgloaded)"/>


Test in Firefox, found good, sure enough and the expected effect, after the picture is downloaded, it will pop up the width of the image. No matter how many times you click or refresh the results are the same.

However, do this step, don't be happy too early-also need to consider the browser compatibility, so, quickly to IE inside test. Yes, it also pops up the width of the image. However, when you click Load again, the situation is different and nothing happens. Refresh, and the same is true.

After testing multiple browser versions, IE6 and opera were found to be the same, while Firefox and Safari behaved normally. In fact, the reason is quite simple, because the browser cache. Once the picture has been loaded once, if there is another request for the picture, because the browser has already cached the image, it will not initiate a new request again, but is loaded directly from the cache. For both Firefox and Safari, the view makes the two loading methods transparent to the user, which also causes the OnLoad event of the picture, while IE and opera ignore this identity and do not cause the image's OnLoad event, so the above code cannot be implemented in them.

What do we 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, the status value directly indicates that it has been downloaded, while loading from the HTTP request, because it needs to wait for the download, this value is displayed as incomplete. In that case, you can take care of it.

After some analysis, we finally found a property--complete for the image that is compatible with each browser. So, before the image onload event, make a judgment on this value. Finally, the code changes to look like this:

Copy CodeThe code is as follows:
function LoadImage (URL, callback) {
var img = new Image (); Create an Image object that enables pre-download of pictures
img.src = URL;
if (img.complete) {//If the picture already exists in the browser cache, call the callback function directly
Callback.call (IMG);
Return Return directly without handling the OnLoad event
}
Img.onload = function () {/////The picture is downloaded asynchronously when callback functions are called.
Callback.call (IMG);//Replace this callback function with the image object
};
};


After such a toss-up, it is finally let each browser can meet our goal. Although the code is simple, but the most important problem in the picture browser is solved, and then you have to do is just how the picture presented the question next look at another way:

Copy CodeThe code is as follows:


<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
<meta http-equiv= "Content-type" content= "text/html; charset=gb2312 "/>
<title>js implement actions after loading the picture preloaded </title>
<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></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 (' banner.html ');//write your own action here,
}
}

JS implementation picture pre-loading without waiting

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.