Let's talk about the javascript image pre-loading technology (detailed demonstration)

Source: Internet
Author: User

The pre-loading technology mentioned in this article mainly enables javascript to quickly obtain the size of the image header data.

A typical example of getting the image size through pre-loading:Copy codeCode: 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;
};
};
};

We can see that the onload method must wait until the image is loaded, and the speed is not flattering.
Different from desktop applications, web applications provide the best response speed. If you want to achieve both speed and elegance, you must obtain the image size in advance. How can you obtain the image size before loading the image?
More than a decade of online experience tells me that when loading images in a browser, you will see that the images will take up a lot of space before loading them, in addition, most of the images here do not have the default width and height attributes, because the browser can obtain the image header data. Based on this, you only need to use javascript to regularly detect the size status of the image to know that the image size is ready.
Implementation Code ):
Update:
Only one timer is used to optimize the performance.
Copy codeThe Code is as follows :/*!
* Img ready v0.3
* Http://www.planeart.cn /? P = 1121
* TangBin-MIT Licensed
*/
// The upload readiness event of the Image Header
// @ Param {String} image path
// @ Param {Function} callback Function for obtaining the size (parameter 1 receives width; parameter 2 receives height)
// @ Param {Function} load the wrong callback Function (optional)
(Function (){
Var list = [], intervalId = null,
Tick = function (){
Var I = 0;
For (; I <list. length; 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, the cached data is directly returned.
If (img. complete) return callback (img. width, img. height );
// Insert a hidden image into the page to monitor whether the image occupies a space
Div = doc. createElement ('div ');
Div.style.css Text = 'visibility: hidden; position: absolute; left: 0; top: 0; width: 1px; height: 1px; overflow: Den den ';
Div. appendChild (img)
Container. appendChild (div );
Width = img. offsetWidth;
Height = img. offsetHeight;
// Events that have been fully loaded
Img. onload = function (){
End ();
Callback (img. width, img. height );
};
// Load the event after the 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 complete
// Delete elements and events to avoid IE Memory leakage
End = function (){
Check. end = true;
Img. onload = img. onerror = null;
Div. innerHTML = '';
Div. parentNode. removeChild (div );
};
// Add the function for checking whether the image is placeholder to the timer queue for regular execution
// Add only one detector to the same image
// Only one timer is allowed at a time to reduce the performance loss of the browser.
! Check. end & check ();
For (var I = 0; I <list. length; I ++ ){
If (list [I]. url === url) return;
};
If (! Check. end ){
List. push (check );
If (! IntervalId) intervalId = setInterval (tick, 150 );
};
};
})();

Is it easy? In this way, the speed of obtaining photography-level photos is usually dozens of times higher than that of onload. However, for normal web (within 800 × 600) browsing-level images, the effect of flash can be achieved.
Well, please watch the pleasant DEMO: http://demo.jb51.net/js/2011/imgready/
(Tested browsers: Chrome, Firefox, Safari, Opera, IE6, IE7, and IE8)
From: Tang Bin

Related Article

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.