search
HomeWeb Front-endJS TutorialLet's talk about javascript image preloading technology again (detailed demonstration)_javascript skills

The preloading technology mentioned in this article mainly allows JavaScript to quickly obtain the size of the image header data.

A typical example of using preloading to obtain the image size:

Copy the code The code is as follows:

var imgLoad = function (url, callback) {
var img = new Image();
img.src = url;
if (img.complete) {
callback (img.width, img.height);
} else {
img.onload = function () {
callback(img.width, img.height);
img.onload = null;
};
};
};

You can see that using onload requires waiting for the image to be loaded, and its speed cannot be complimented.
Web applications are different from desktop applications, and response speed is the best user experience. If you want both speed and elegance, you must obtain the image size in advance. How can you obtain the image size before the image is loaded?
More than ten years of Internet experience tells me: when the browser loads images, you will see that the images will first occupy a piece of land and then slowly load, and most of the images here do not have preset width and height. Attribute, because the browser can obtain the header data of the image. Based on this, you only need to use javascript to regularly detect the size status of the image to know the image size ready status.
Implementation code (updated on 2011-03-11):
2011-03-12 updated:
Only use a certain timer to optimize performance
Copy code The code is as follows:

/*!
* img ready v0.3
* http://www .planeart.cn/?p=1121
* TangBin - MIT Licensed
*/
// Image header data loading ready event
// @param {String} image path
// @param {Function} The callback function for getting the size (parameter 1 receives width; parameter 2 receives height)
// @param {Function} The callback function for loading errors (optional)
(function () {
var list = [], intervalId = null,
tick = function () {
var i = 0;
for (; i list[i ].end ? list.splice(i--, 1) : list[i]();
};
!list.length && stop();
},
stop = function () {
clearInterval(intervalId);
intervalId = null;
};
this.imgReady = function (url, callback, error) {
var check, end, width, height , offsetWidth, offsetHeight, div,
accuracy = 1024,
doc = document,
container = doc.body || doc.getElementsByTagName('head')[0],
img = new Image ();
img.src = url;
if (!callback) return img;
// If the image is cached, return the cached data directly
if (img.complete) return callback( img.width, img.height);
// Insert a secret image into the page to monitor whether the image takes up space
div = doc.createElement('div');
div.style.cssText = 'visibility:hidden;position:absolute;left:0;top:0;width:1px;height:1px;overflow:hidden';
div.appendChild(img)
container.appendChild(div);
width = img.offsetWidth;
height = img.offsetHeight;
// Completely loaded event
img.onload = function () {
end();
callback( img.width, img.height);
};
// Event after loading error
img.onerror = function () {
end();
error && error() ;
};
// Check whether the image has been occupied
check = function () {
offsetWidth = img.offsetWidth;
offsetHeight = img.offsetHeight;
if (offsetWidth !== width || offsetHeight !== height || offsetWidth * offsetHeight > accuracy) {
end();
callback(offsetWidth, offsetHeight);
};
};
check.url = url;
// Clean up after the operation is completed
// Delete elements and events to avoid IE memory leaks
end = function () {
check.end = true;
img.onload = img.onerror = null;
div.innerHTML = '';
div.parentNode.removeChild(div);
};
// Will detect whether the image is a placeholder The function is added to the timer queue for regular execution
// Only one detector is added to the same picture
// Only one timer is allowed to appear at any time to reduce browser performance loss
!check.end && check( );
for (var i = 0; i if (list[i].url === url) return;
};
if ( !check.end) {
list.push(check);
if (!intervalId) intervalId = setInterval(tick, 150);
};
};
})() ;

Isn’t it very simple? The speed of obtaining photographic-level photo sizes in this way is often dozens of times that of the onload method, and it can achieve a flash sale effect for ordinary web browsing-level pictures (within 800×600).
Okay, please watch the delightful DEMO: http://demo.jb51.net/js/2011/imgready/
(Tested browsers: Chrome, Firefox, Safari, Opera, IE6, IE7, IE8)
From:: Tang Bin
Statement
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
Replace String Characters in JavaScriptReplace String Characters in JavaScriptMar 11, 2025 am 12:07 AM

Detailed explanation of JavaScript string replacement method and FAQ This article will explore two ways to replace string characters in JavaScript: internal JavaScript code and internal HTML for web pages. Replace string inside JavaScript code The most direct way is to use the replace() method: str = str.replace("find","replace"); This method replaces only the first match. To replace all matches, use a regular expression and add the global flag g: str = str.replace(/fi

jQuery Check if Date is ValidjQuery Check if Date is ValidMar 01, 2025 am 08:51 AM

Simple JavaScript functions are used to check if a date is valid. function isValidDate(s) { var bits = s.split('/'); var d = new Date(bits[2] '/' bits[1] '/' bits[0]); return !!(d && (d.getMonth() 1) == bits[1] && d.getDate() == Number(bits[0])); } //test var

jQuery get element padding/marginjQuery get element padding/marginMar 01, 2025 am 08:53 AM

This article discusses how to use jQuery to obtain and set the inner margin and margin values ​​of DOM elements, especially the specific locations of the outer margin and inner margins of the element. While it is possible to set the inner and outer margins of an element using CSS, getting accurate values ​​can be tricky. // set up $("div.header").css("margin","10px"); $("div.header").css("padding","10px"); You might think this code is

10 jQuery Accordions Tabs10 jQuery Accordions TabsMar 01, 2025 am 01:34 AM

This article explores ten exceptional jQuery tabs and accordions. The key difference between tabs and accordions lies in how their content panels are displayed and hidden. Let's delve into these ten examples. Related articles: 10 jQuery Tab Plugins

10 Worth Checking Out jQuery Plugins10 Worth Checking Out jQuery PluginsMar 01, 2025 am 01:29 AM

Discover ten exceptional jQuery plugins to elevate your website's dynamism and visual appeal! This curated collection offers diverse functionalities, from image animation to interactive galleries. Let's explore these powerful tools: Related Posts: 1

HTTP Debugging with Node and http-consoleHTTP Debugging with Node and http-consoleMar 01, 2025 am 01:37 AM

http-console is a Node module that gives you a command-line interface for executing HTTP commands. It’s great for debugging and seeing exactly what is going on with your HTTP requests, regardless of whether they’re made against a web server, web serv

Custom Google Search API Setup TutorialCustom Google Search API Setup TutorialMar 04, 2025 am 01:06 AM

This tutorial shows you how to integrate a custom Google Search API into your blog or website, offering a more refined search experience than standard WordPress theme search functions. It's surprisingly easy! You'll be able to restrict searches to y

jquery add scrollbar to divjquery add scrollbar to divMar 01, 2025 am 01:30 AM

The following jQuery code snippet can be used to add scrollbars when the div content exceeds the container element area. (No demonstration, please copy it directly to Firebug) //D = document //W = window //$ = jQuery var contentArea = $(this), wintop = contentArea.scrollTop(), docheight = $(D).height(), winheight = $(W).height(), divheight = $('#c

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools