


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:
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
/*!
* 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

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

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

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

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

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-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

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

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


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

SublimeText3 Chinese version
Chinese version, very easy to use

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

Dreamweaver Mac version
Visual web development tools
