JS 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('aaa.jpg',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/imghw/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('banner.html');//这里写自己的动作吧, } }

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



How to use JS and Baidu Map to implement map pan function Baidu Map is a widely used map service platform, which is often used in web development to display geographical information, positioning and other functions. This article will introduce how to use JS and Baidu Map API to implement the map pan function, and provide specific code examples. 1. Preparation Before using Baidu Map API, you first need to apply for a developer account on Baidu Map Open Platform (http://lbsyun.baidu.com/) and create an application. Creation completed

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

How to use PHP and JS to create a stock candle chart. A stock candle chart is a common technical analysis graphic in the stock market. It helps investors understand stocks more intuitively by drawing data such as the opening price, closing price, highest price and lowest price of the stock. price fluctuations. This article will teach you how to create stock candle charts using PHP and JS, with specific code examples. 1. Preparation Before starting, we need to prepare the following environment: 1. A server running PHP 2. A browser that supports HTML5 and Canvas 3

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

Overview of how to use JS and Baidu Maps to implement map click event processing: In web development, it is often necessary to use map functions to display geographical location and geographical information. Click event processing on the map is a commonly used and important part of the map function. This article will introduce how to use JS and Baidu Map API to implement the click event processing function of the map, and give specific code examples. Steps: Import the API file of Baidu Map. First, import the file of Baidu Map API in the HTML file. This can be achieved through the following code:

How to use JS and Baidu Maps to implement the map heat map function Introduction: With the rapid development of the Internet and mobile devices, maps have become a common application scenario. As a visual display method, heat maps can help us understand the distribution of data more intuitively. This article will introduce how to use JS and Baidu Map API to implement the map heat map function, and provide specific code examples. Preparation work: Before starting, you need to prepare the following items: a Baidu developer account, create an application, and obtain the corresponding AP

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

How to use JS and Baidu Maps to implement map polygon drawing function. In modern web development, map applications have become one of the common functions. Drawing polygons on the map can help us mark specific areas for users to view and analyze. This article will introduce how to use JS and Baidu Map API to implement map polygon drawing function, and provide specific code examples. First, we need to introduce Baidu Map API. You can use the following code to import the JavaScript of Baidu Map API in an HTML file
