Understanding Javascript image pre-loading and javascript image loading

Source: Internet
Author: User
Tags intl tld

Understanding Javascript image pre-loading and javascript image loading

Pre-loading images is a good way to improve user experience. When images are pre-loaded into the browser, visitors can smoothly surf your website and enjoy extremely fast loading. This is very advantageous for websites with a large proportion of image galleries and images. It ensures fast and seamless publishing of images, it can also help users get a better user experience when browsing the content of your website. This article will share three different pre-loading technologies to enhance the website's performance and availability.

Method 1:Implement pre-loading with CSS and JavaScript

There are many ways to implement pre-loading images, including using CSS, JavaScript, and various combinations of the two. These technologies can be used to design corresponding solutions based on different design scenarios, which is very efficient.

With CSS alone, you can easily and efficiently pre-load images. The Code is as follows:

#preload-01 { background: url(http://domain.tld/image-01.png) no-repeat -9999px -9999px; }#preload-02 { background: url(http://domain.tld/image-02.png) no-repeat -9999px -9999px; }#preload-03 { background: url(http://domain.tld/image-03.png) no-repeat -9999px -9999px; } 

Apply the three ID selectors to the (X) HTML element. Then, we can pre-load the image to the background outside the screen through the background attribute of CSS. As long as the paths of these images remain unchanged, when they are called elsewhere on the web page, the browser will use pre-loaded (cached) images during rendering. Simple and efficient, without any JavaScript.

Although this method is efficient, there is still room for improvement. The image loaded with this method is loaded together with other content on the page, increasing the overall loading time of the page. To solve this problem, we added some JavaScript code to delay the pre-loading time until the page loading is complete. The Code is as follows:

function preloader() {  if (document.getElementById) {    document.getElementById("preload-01").style.background = "url(http://domain.tld/image-01.png) no-repeat -9999px -9999px";    document.getElementById("preload-02").style.background = "url(http://domain.tld/image-02.png) no-repeat -9999px -9999px";    document.getElementById("preload-03").style.background = "url(http://domain.tld/image-03.png) no-repeat -9999px -9999px";  }}function addLoadEvent(func) {  var oldonload = window.onload;  if (typeof window.onload != 'function') {    window.onload = func;  } else {    window.onload = function() {      if (oldonload) {        oldonload();      }      func();    }  }}addLoadEvent(preloader);

In the first part of the script, we obtain the elements using the class selector and set the background attribute for it to pre-load different images.

In the second part of the script, we use the addLoadEvent () function to delay the loading time of the preloader () function until the page is loaded.

What happens if JavaScript cannot run normally in your browser? Very simple. images are not pre-loaded. When the page calls images, they are displayed normally.

Method 2:Use JavaScript only for pre-loading

The above method is sometimes very efficient, but we gradually find that it will take too much time in the actual implementation process. On the contrary, I prefer to use pure JavaScript to implement image pre-loading. The following two pre-loading methods are provided, which can work well on all modern browsers.

JavaScript code segment 1

You only need to simply edit and load the path and name of the image you want. This is easy to implement:

<div class="hidden">  <script type="text/javascript">      var images = new Array()      function preload() {        for (i = 0; i < preload.arguments.length; i++) {          images[i] = new Image()          images[i].src = preload.arguments[i]        }      }      preload(        "http://domain.tld/gallery/image-001.jpg",        "http://domain.tld/gallery/image-002.jpg",        "http://domain.tld/gallery/image-003.jpg"      )  </script></div>

This method is especially suitable for pre-loading a large number of images. My gallery website uses this technology to pre-load more than 50 images. Apply the script to the logon page. Most gallery images are pre-loaded as long as the user enters the Logon account.

JavaScript code segment 2

This method is similar to the preceding method. You can also pre-load any number of images. Add the following script to any web page and edit it according to the program instructions.

<div class="hidden">  <script type="text/javascript">      if (document.images) {        img1 = new Image();        img2 = new Image();        img3 = new Image();        img1.src = "http://domain.tld/path/to/image-001.gif";        img2.src = "http://domain.tld/path/to/image-002.gif";        img3.src = "http://domain.tld/path/to/image-003.gif";      }  </script></div> 

As you can see, each time you load an Image, you need to create a variable, such as "img1 = new Image ();" and the source Image address Declaration, such as "img3.src = ".. /path/to/image-003.gif ";". Refer to this mode to load any number of images as needed.

We have also improved this method. Encapsulate the script into a function and use addLoadEvent () to delay the pre-loading time until the page is loaded.

function preloader() {  if (document.images) {    var img1 = new Image();    var img2 = new Image();    var img3 = new Image();    img1.src = "http://domain.tld/path/to/image-001.gif";    img2.src = "http://domain.tld/path/to/image-002.gif";    img3.src = "http://domain.tld/path/to/image-003.gif";  }}function addLoadEvent(func) {  var oldonload = window.onload;  if (typeof window.onload != 'function') {    window.onload = func;  } else {    window.onload = function() {      if (oldonload) {        oldonload();      }      func();    }  }}addLoadEvent(preloader);

Method 3:Use Ajax for pre-loading

The method shown above does not seem cool enough. Now let's look at a method that uses Ajax to implement image pre-loading. This method uses DOM to not only pre-load images, but also pre-load CSS, JavaScript and other related things. The advantage of using Ajax is that loading JavaScript and CSS does not affect the current page. This method is simple and efficient.

window.onload = function() {  setTimeout(function() {    // XHR to request a JS and a CSS    var xhr = new XMLHttpRequest();    xhr.open('GET', 'http://domain.tld/preload.js');    xhr.send('');    xhr = new XMLHttpRequest();    xhr.open('GET', 'http://domain.tld/preload.css');    xhr.send('');    // preload image    new Image().src = "http://domain.tld/preload.png";  }, 1000);};

The response code predefines the response preload.js?##preload.css=and response preload.png ". 1000 milliseconds of timeout is used to prevent the script from being suspended, leading to functional problems on normal pages.

Next, let's take a look at how to use JavaScript to implement the loading process:

window.onload = function() {   setTimeout(function() {     // reference to 

Here, we use DOM to create three elements to implement pre-loading of three files. As mentioned above, with Ajax, file loading will not be applied to page loading. From this point of view, the Ajax method is superior to JavaScript.

Supplement:Callback Function after loading

Let's write the following code:

Function loadImage (url, callback) {var img = new Image (); img. src = url; img. onload = function () {// call the callback function asynchronously when the image is downloaded. Callback. call (img); // switch the callback function this pointer to img. };}

Test it in firefox and find it is good. It is indeed the same as expected. After the image is downloaded, the image width will pop up. The results are the same no matter how many clicks or refreshes.

However, to do this, don't be too happy-you still need to consider the compatibility of the browser, so hurry to test it in ie. That's right. The image width is also displayed. However, when you click load again, the situation is different and no response is returned. Refresh the page.

After tests on multiple browser versions, we found that ie6 and opera both work like this, while firefox and safari work normally. In fact, the reason is quite simple, that is, the browser cache. After an image is loaded once, if a request is sent to the image again, the browser will not initiate a new request because the image has been cached, instead, it is directly loaded from the cache. For firefox and safari, their views make the two loading methods transparent to users, and will also cause image onload events, while ie and opera ignore this identity, it does not start the onload event of images, so the above Code cannot achieve the effect in them.

What should we do? The best case is that the Image may have a status value indicating whether it has been loaded successfully. When loading from the cache, because you do not need to wait, this status value directly indicates that it has been downloaded. When loading from an http request, this value is not displayed because you need to wait for download. In this way, you can do it.

After some analysis, we finally found a property of the Image compatible with various browsers-complete. Therefore, make a judgment on this value before the image onload event. Finally, the Code becomes as follows:

Function loadImage (url, callback) {var img = new Image (); // create an Image object to implement pre-download of the Image img. src = url; if (img. complete) {// if the image already exists in the browser cache, call the callback function callback directly. call (img); return; // direct return, no need to process onload event} img. onload = function () {// call the callback function asynchronously when the image is downloaded. Callback. call (img); // replace this of the callback function with an Image object };};

Although the code is simple, it is very practical.

Appendix: javascript image pre-loading

The lightbox effect is pre-loaded to enable the picture to be displayed in the center. You need to wait until it is fully loaded to display the effect. The experience is poor (such as the full screen effect of the filick album ). Javascript cannot obtain the imgfile header data. Is that true? This article uses a clever method for javascript to obtain it.

This is an example of how most people use the pre-loading method 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

The above must wait until the image is loaded to obtain the size, the speed is not flattering, we need to improve.

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 piece of space before loading them. You do not need to preset the width and height attributes, 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 that the image size is ready.

Of course, there will actually be some compatibility traps, such as the inconsistency between width and height detection in various browsers, and the images created by webkit new Image () will be affected by the URLs in the loading process, the best solution after repeated tests:

// Update: // 05.27: 1. Ensure the callback execution sequence: error> ready> load; 2. the callback function this points to the img itself // 04-02: 1. Increase the callback after the image is fully loaded 2. Improve the performance/*** the image header data loading readiness event-get the image size faster * @ version 2011.05.27 * @ author TangBin * @ see http://www.planeart.cn /? P = 1121 * @ param {String} image path * @ param {Function} Ready size * @ param {Function} loaded (optional) * @ param {Function} loading error (optional) * @ example imgReady ('HTTP: // www.google.com.hk/intl/zh-CN/images/logo_cn.png', function () {alert ('size ready: width = '+ this. width + '; height =' + this. height) ;}); */var imgReady = (function () {var list = [], intervalId = null, // used to run the queue tick = function () {var I = 0; for (; I <l Ist. length; I ++) {list [I]. end? List. splice (I --, 1): list [I] () ;};! List. length & stop () ;}, // stop all timer queues stop = function () {clearInterval (intervalId); intervalId = null ;}; return function (url, ready, load, error) {var onready, width, height, newWidth, newHeight, img = new Image (); img. src = url; // if the image is cached, the cached data if (img. complete) {ready. call (img); load & load. call (img); return ;}; width = img. width; height = img. height; // load the error event img. onerror = functi On () {error & error. call (img); onready. end = true; img = img. onload = img. onerror = null ;}; // image size ready onready = function () {newWidth = img. width; newHeight = img. height; if (newWidth! = Width | newHeight! = Height | // if the image has been loaded elsewhere, use area detection newWidth * newHeight> 1024) {ready. call (img); onready. end = true ;};}; onready (); // fully loaded event img. onload = function () {// onload may be faster than onready In the timer time difference range. // check here and ensure that onready is executed preferentially! Onready. end & onready (); load & load. call (img); // The ie gif animation executes onload cyclically and sets the onload to img = img. onload = img. onerror = null ;}; // periodically execute if (! Onready. end) {list. push (onready); // only one timer is allowed at a time, reducing browser performance loss if (intervalId = null) intervalId = setInterval (tick, 40 );};};})();

Call example:

imgReady('http://www.google.com.hk/intl/zh-CN/images/logo_cn.png', function () {  alert('size ready: width=' + this.width + '; height=' + this.height);});

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.

Articles you may be interested in:
  • Javascript is also used to play with image pre-loading.
  • Let's talk about the javascript image pre-loading technology (detailed demonstration)
  • Js achieves Image pre-loading (js operates Image object attribute complete, event onload asynchronously loads images)
  • JS image pre-loading JS to implement image pre-loading applications
  • JS achieves image pre-loading without waiting
  • Efficient image pre-loading using CSS, JavaScript, and Ajax
  • Js image pre-loading example
  • Javascript to implement image pre-loading
  • Javascript image pre-loading instance analysis

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.