Understanding JavaScript picture preload _javascript tips

Source: Internet
Author: User
Tags tld browser cache

Pre-loading pictures are a great way to improve the user experience. The picture is preloaded into the browser, and visitors can surf the site smoothly and enjoy a very fast loading speed. This is good for a large percentage of the picture galleries and pictures, which ensures that the images are released quickly and seamlessly, and can help users gain a better user experience when browsing through your site's content. This article will share three different preload technologies to enhance the performance and usability of your site.

method One: pre-loading with CSS and JavaScript

There are many ways to implement preloaded images, including using CSS, JavaScript, and a combination of both. These technologies can be designed according to different design scenarios for the corresponding solution, very efficient.

The simple use of CSS, you can easily and efficiently preload the picture, the code is as follows:

#preload -01 {background:url (yun_qi_img/image-01.png) no-repeat-9999px-9999px}
#preload -02 {background:url (yun_qi_img/image-02.png) no-repeat-9999px-9999px}

By applying these three ID selectors to (X) HTML elements, we can preload the picture onto the background outside the screen with the background property of the CSS. As long as the paths of these pictures remain unchanged, and when they are invoked elsewhere in the Web page, the browser uses the preloaded (cached) picture during the rendering process. Simple, efficient, and does not require any javascript.

Although the method is efficient, there is still room for improvement. The images loaded with this method are loaded together with the other contents of the page, which increases the overall load time of the page. To solve this problem, we added some JavaScript code to postpone the preload time until the page loads. The code is as follows:

function Preloader () {
  if (document.getElementById) {
    document.getElementById ("preload-01"). style.background = "url (yun_qi_img/image-01.png) no-repeat-9999px-9999px";
    document.getElementById ("preload-02"). Style.background = "url (yun_qi_img/image-02.png) no-repeat-9999px-9999px";
    document.getElementById ("preload-03"). Style.background = "url (yun_qi_img/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 get the element that uses the class selector and set the Background property to preload the different pictures.

In the second part of the script, we use the addloadevent () function to delay the load time of the Preloader () function until the page has finished loading.

What happens if JavaScript doesn't work in the user's browser? Very simple, the picture will not be preloaded, when the page calls the picture, the normal display can be.

Method Two: pre-loading using JavaScript only

The above methods are sometimes very efficient, but we gradually find that it takes too much time in the actual implementation process. Instead, I prefer to use pure JavaScript to get the picture preloaded. Here are two of these preload methods that can work beautifully on all modern browsers.

JavaScript code Snippet 1

Simply edit and load the path and name of the desired picture, which is easy to achieve:

<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 = Preloa D.arguments[i]
        }
      preload (
        "yun_qi_img/image-001.jpg",
        "Yun_qi_img/image-002.jpg",
        "Yun_qi_img/image-003.jpg"
      )
  </script>
</div>

This method is especially suitable for preload a large number of pictures. My gallery site uses this technology to preload more than 50 pictures. Apply the script to the login page, and most gallery images will be preloaded as long as the user enters the login account.

JavaScript code Snippet 2

This method is similar to the method above and can be preloaded with any number of pictures. 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 = "Yun_qi_img/image-001.gif";
        IMG2.SRC = "Yun_qi_img/image-002.gif";
        IMG3.SRC = "Yun_qi_img/image-003.gif";
      }
  </script>
</div>
 

As you can see, each load of a picture needs to create a variable, such as "IMG1 = new Image ();", and a picture source address declaration, such as "IMG3.SRC =". /path/to/image-003.gif ";". Depending on the pattern, you can load as many pictures as you want.

We have also improved the method. Encapsulate the script into a function and use addloadevent () to defer preload 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 = "Yun_qi_img/image-001.gif";
    IMG2.SRC = "Yun_qi_img/image-002.gif";
    IMG3.SRC = "Yun_qi_img/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 Three: pre-loading using AJAX

The method given above doesn't seem cool enough, so let's look at a way to preload a picture using Ajax. This method uses DOM, not only preload pictures, but also preload CSS, JavaScript and other related things. The advantage of using AJAX, rather than using JavaScript directly, is that the loading of JavaScript and CSS does not affect the current page. The method is simple and efficient.

Window.onload = function () {
  settimeout (function () {
    //XHR to request a JS and a CSS
    var XHR = new Xmlhttpreq Uest ();
    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 = "yun_qi_img/preload.png";
  }, 1000);

The code above is preloaded with "preload.js", "Preload.css", and "Preload.png". The 1000-millisecond timeout was designed to prevent the script from hanging, causing a functional problem with the normal page.

Let's look at how to implement the loading process with javascript:

Window.onload = function () {
 
  settimeout (function () {
 
    //reference to  
 

Here, we create three elements from the DOM to implement the preload of three files. As mentioned above, using AJAX, loading files are not applied to the loading page. From this point of view, the AJAX approach is superior to JavaScript.

add: Load callback function

We write the following code:

function LoadImage (URL, callback) {
 var img = new Image ();
 img.src = URL;

 Img.onload = function () {////callback functions are called asynchronously when the picture is downloaded.
  Callback.call (IMG);  Switch the callback function this pointer to IMG.
 };
}

In Firefox test, found good, and sure enough, as expected effect, in the picture after downloading, will pop up the width of the picture. No matter how many times you click or refresh results are the same.

However, do this step, don't be too early to be happy-also need to consider browser compatibility, so, quickly to IE inside test. Yes, it also pops up the width of the picture. However, when you click Load, the situation is different and nothing happens. Refresh, the same is true.

After a number of browser versions of the test, found that IE6, opera will do, and Firefox and Safari are behaving normally. In fact, the reason is very simple, because the browser cache. Once the picture has been loaded once, if there is another request for the picture, because the browser has already cached the picture, it will not initiate a new request, but simply load it from the cache. For Firefox and Safari, their views make these two loading methods transparent to the user, also cause the image of the OnLoad event, while IE and opera ignore this identity, does not cause the image of the OnLoad event, so the above code in them can not be achieved.

What do we do? The best case scenario is that image can have a status value indicating whether it has been loaded successfully. When loading from the cache, the status value is directly indicated to have been downloaded, and when loading from the HTTP request because it does not need to wait, the value appears to be incomplete. In that case, it will be done.

After some analysis, we finally found a property--complete for the image that is compatible with each browser. So, before the photo onload event, make a judgment on this value first. Finally, the code becomes as follows:

function LoadImage (URL, callback) {
  var img = new Image ()////Create an Image object to implement the download
  img.src = URL of the picture;
  
  if (img.complete) {//If the picture already exists in the browser cache, call the callback function directly
    Callback.call (IMG);
    Return Return directly without handling the OnLoad event
  }

  img.onload = function () {//callback functions are called asynchronously when the picture is downloaded.
    Callback.call (IMG);//replaces this of the callback function with the image Object
  };


Although the code is simple, it is practical.

Attach: Again talk JavaScript picture preload

Lightbox class effects use preload to center the picture and need to wait for the full load to be displayed and experience poorly (such as the full screen effect of the Filick album). JavaScript cannot get IMG header data, is that really the case? This article is an ingenious way to get JavaScript to get it.

This is an example of how most people use preload to get the size of a picture:

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;
;}; Can see

The above must wait for the picture to be loaded to get the size, its speed is not flattering, we need to improve.

Web applications differ from desktop applications, and response speed is the best user experience. If you want speed and elegance, you must get the picture size in advance, how to get the picture size when the picture is not loaded?

More than 10 years of Internet experience tells me: the browser when loading pictures you will see the picture will occupy a piece of land before slowly loaded, and do not need to preset width and height properties, because the browser can get the image of the head data. Based on this, it is only necessary to use JavaScript to detect the size state of a picture in a timely state.

Of course there will be some compatible traps, such as width and height to detect the inconsistencies of each browser, as well as WebKit new image () created by the image in the loading process with the URL image, after repeated testing the best way to deal with:

Update://05.27:1, ensure callback execution order: error > Ready > Load;2, callback function this point to IMG itself//04-02:1, increase the picture after full load callback 2, raise high-performance/** * Image Header Data loading  Thread events-Faster get picture size * @version 2011.05.27 * @author tangbin * @see http://www.planeart.cn/?p=1121 * @param {String} Picture path * @param {function} size ready * @param {function} loaded (optional) * @param {function} load error (optional) * @example imgready (' Y
  Un_qi_img/logo_cn.png ', function () {alert (' size ready:width= ' + this.width + '; height= ' + this.height);
 });
    * * var Imgready = (function () {var list = [], intervalid = NULL,//used to execute queue tick = function () {var i = 0;
    for (; i < list.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; Such asIf the image is cached, it returns the cached data directly to the IF (img.complete) {Ready.call (IMG);
      Load && load.call (IMG);
    Return
    
    };
    width = img.width;
    
    Height = img.height;
      Event Img.onerror = function () {Error && Error.call (IMG) After loading error
      Onready.end = true;
    img = img.onload = Img.onerror = null;
    
    };
      Picture size Ready Onready = function () {newwidth = Img.width;
      Newheight = Img.height;
        if (newwidth!== width | | | newheight!== Height | |
        If the picture has been loaded elsewhere the usable area detects Newwidth * newheight > 1024) {ready.call (IMG);
      Onready.end = true;
    };
    };
    
    Onready (); Fully Loaded event Img.onload = function () {//onload may be inspected in the timer time difference than onready fast//here and ensure that Onready priority is enforced!onre
    
      Ady.end && Onready ();
      
      Load && load.call (IMG);
    IE gif animation will loop to execute onload, empty onload can be img = img.onload = Img.onerror = null;

    }; To join a queue to perform a periodic if (!onready.end)
      {List.push (Onready);
    Whenever only one timer is allowed, reduce browser performance loss if (Intervalid = = null) Intervalid = SetInterval (tick, 40);
  };
};

 })();

Call Example:

Imgready (' Yun_qi_img/logo_cn.png ', function () {
  alert (' Size ready:width= ' + this.width + '; height= ' + this.height);
});

Is it simple? This way to get photographic level photo size is often more than 10 times the OnLoad method, and the Web Normal (800x600) browsing level of the image can achieve a second kill effect.

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.