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

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.


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

SublimeText3 Linux new version
SublimeText3 Linux latest version

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Notepad++7.3.1
Easy-to-use and free code editor
