Three methods of picture preloading using CSS JavaScript and Ajax

  • 2021-07-13 04:14:27
  • OfStack

Preloading pictures is a good way to improve the user experience. Images are pre-loaded into the browser, so visitors can surf your website smoothly and enjoy extremely fast loading speed. This is a 10-point advantage for photo galleries and websites with a large proportion of photos. It ensures that photos are published quickly and seamlessly, and it can also help users get a better user experience when browsing your website content. This article will share three different preloading technologies to enhance the performance and usability of websites.

Method 1: Preload with CSS and JavaScript

There are many ways to preload images, including using CSS, JavaScript, and various combinations of the two. These technologies can design corresponding solutions according to different design scenarios, with 10 points of high efficiency.

Using CSS alone, you can easily and efficiently preload pictures. The code is as follows:


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

By applying these three ID selectors to the X) HTML element, we can preload the picture onto the off-screen background through the background attribute of CSS. As long as the path of these pictures remains the same, when they are called elsewhere on the Web page, the browser will use the preloaded (cached) pictures during rendering. Simple and efficient, without any JavaScript. Although this method is efficient, there is still room for improvement. Images loaded by this method are loaded together with other contents of the page, which increases the overall loading time of the page. To solve this problem, we added a bit of JavaScript code to delay the preload until the page is loaded. The code is as follows:


function preloader() {
  if (document.getElementById) {
    document.getElementById("p1").style.background = "url(image-01.png) no-repeat";
    document.getElementById("p2").style.background = "url(image-02.png) no-repeat";
    document.getElementById("p3").style.background = "url(image-03.png) no-repeat";
  }
}
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 Part 1 of the script, we get the element that uses the class selector and set the background attribute for it to preload different pictures.

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

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

Method 2: Preload only using JavaScript

The above method is sometimes very efficient, but we gradually find that it takes too much time in the actual implementation process. On the contrary, I prefer to use pure JavaScript to preload pictures. Here are two such preloading methods that work beautifully on all modern browsers.

JavaScript Code Snippet 1


<div class="hidden">
  <script type="text/javascript">
    <!--//--><![CDATA[//><!--
      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>

Simply edit and load the path and name of the required picture, which is easy to realize:

This method is especially suitable for preloading a large number of pictures. My gallery website uses this technology, and the number of pre-loaded pictures reaches more than 50. Apply this 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


<div class="hidden">
  <script type="text/javascript">
    <!--//--><![CDATA[//><!--
      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>

This method is similar to the above method, and any number of pictures can be preloaded. Add the following script to any Web page and edit it according to the program instructions.

As you can see, you need to create a variable for every image loaded, such as "img1 = new Image ();" And the image source address statement, such as "img3.src ="../path/to/image-003. gif ";" . Referring to this mode, you can load as many pictures as you need.

We also improve the method. Encapsulate the script in a function and use addLoadEvent () to delay the preload 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: Preload with Ajax

The method given above seems not cool enough, so let's look at a method to preload pictures using Ajax. This method uses DOM to preload not only pictures, but also CSS, JavaScript and other related things. The advantage of using Ajax over using JavaScript directly is that the loading of JavaScript and CSS will 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 above code preloads "preload. js", "preload. css", and "preload. png". The 1000-millisecond timeout prevents scripts from hanging and causing functional problems on normal pages.

Next, let's look at how to implement this loading process with JavaScript:


window.onload = function() {
  setTimeout(function() {
    // reference to <head>
    var head = document.getElementsByTagName('head')[0];
    // a new CSS
    var css = document.createElement('link');
    css.type = "text/css";
    css.rel = "stylesheet";
    css.href = "http://domain.tld/preload.css";
    // a new JS
    var js = document.createElement("script");
    js.type = "text/javascript";
    js.src = "http://domain.tld/preload.js";
    // preload JS and CSS
    head.appendChild(css);
    head.appendChild(js);
    // preload image
    new Image().src = "http://domain.tld/preload.png";
  }, 1000);
};

Here, we create three elements through DOM to preload three files. As mentioned above, with Ajax, the load file does not apply to the load page. From this point of view, Ajax method is superior to JavaScript.


Related articles: