JS realize picture preload without waiting _javascript skill

Source: Internet
Author: User
Tags http request browser cache

Web site development often need to achieve a large number of images in a page to browse, if you consider the flow, can be like pconline each page shows only a picture, so that users each look at a picture will need to 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 long time to see other pictures.

Know the address of a picture, need to put it in a fixed size of the HTML container (can be div, etc.) inside display, the most important thing is to know this is about to show the width and height of the picture, and then combine the width and height of the container, according to a certain scale to show the picture. Therefore, the realization of picture preload becomes the core function of the image browser.

has done the picture rollover effect friend actually all knows, wants the picture rotation time does not appear waits, the best is first lets the picture download to the local, lets the browser cache. At this time, the general will use the image object in JS inside. The usual means are nothing more than this:

Copy Code code as follows:

function preloadimg (URL) {
var img = new Image ();
img.src = URL;
}

By calling the Preloadimg function, the URL of the image is passed in so that the picture can be downloaded beforehand. In fact, the pre download functionality used here is basically consistent with this. After downloading the picture, through the img width and Height properties, you can know the picture width and height. However, you need to consider that when you do the image browser function, the picture is displayed in real time. For example, you click on the Display button, this time will call the above similar code to load the picture. Therefore, if you use Img.width directly, the picture has not been completely downloaded. Therefore, it is necessary to use some asynchronous methods, wait until the picture is downloaded, the IMG's width and height will be invoked again.

The implementation of such an asynchronous method is actually not difficult, the picture of the download complete event is also very simple, is the simple onload event. So, we can write the following code:
Copy Code code as follows:

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

OK, let's write a test case.
Copy Code code as follows:

function imgloaded () {
alert (this.width);
}
<input type= "button" value= "LoadImage" onclick= "LoadImage (' aaa.jpg ', imgloaded)"/>

In Firefox test, found good, and sure enough, as expected effect, in the picture after downloading, will pop up the width of the picture. No matter how many times you click or refresh results are the same.

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

After a number of browser versions of the test, found that IE6, opera will do, and Firefox and Safari are behaving normally. In fact, the reason is very 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 picture, it will not initiate a new request, but simply load it from the cache. For Firefox and Safari, their views make these two loading methods transparent to the user, also cause the image of the OnLoad event, while IE and opera ignore this identity, does not cause the image of the OnLoad event, so the above code in them can not be achieved.

What do we do? The best case scenario is that image can have a status value indicating whether it has been loaded successfully. When loading from the cache, the status value is directly indicated to have been downloaded, and when loading from the HTTP request because it does not need to wait, the value appears to be incomplete. In that case, it will be done.

After some analysis, we finally found a property--complete for the image that is compatible with each browser. So, before the photo onload event, make a judgment on this value first. Finally, the code becomes as follows:
Copy Code code as follows:

function LoadImage (URL, callback) {
var img = new Image (); Create an Image object to achieve a pre-download of the picture
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 () {////callback functions are called asynchronously when the picture is downloaded.
Callback.call (IMG);//Replace the callback function with this with an Image object
};
};

After such a toss, finally let each browser can meet our goal. Although the code is very simple, but the image browser to solve the most core problems, and then you have to do is only the picture how the problem of rendering the next look at another way:
Copy Code code 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 "/>
&LT;TITLE&GT;JS implementation of the picture preload after loading action </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]= "Yun_qi_img/baidu_logo.gif";
Imgarr[1]= "Yun_qi_img/logo-img.gif";
Imgarr[2]= "Yun_qi_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,
}
}

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.