Preloading images is a great way to improve the user experience. Images are pre-loaded into the browser, so visitors can surf your site and enjoy extremely fast loading times.

This is great for image galleries and sites that have a high proportion of images, as it ensures fast and seamless distribution of images, and helps users have a better user experience when navigating your content.

This article will share three different preloading techniques to enhance the performance and usability of your web site.

Method 1: Preload with CSS and JavaScript

There are many ways to implement preloading images, including using CSS, JavaScript, and various combinations of the two. These technologies can design solutions according to different design scenarios, which is very efficient.

Preload images easily and efficiently using CSS 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; }
Copy the code

By applying these three ID selectors to the (X) HTML element, we can preload the image to the off-screen background via the CSS background property.

As long as the path of these images remains the same, the browser uses preloaded (cached) images during the rendering process when they are called elsewhere on the Web page. Simple, efficient, and doesn’t require any JavaScript.

Although this method is efficient, there is still room for improvement. Images loaded with this method are loaded along with the rest of the page, increasing the overall page load time.

To solve this problem, we added some JavaScript code that delayed the preloading until the page was loaded. 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);Copy the code

In the first part of the script, we get the element that uses the class selector and set the background property to it to preload the different images.

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

What happens if JavaScript doesn’t work properly in a user’s browser? Very simply, images are not preloaded and display normally when the page calls images.

Method two: Use JavaScript only for preloading

The above approach can be effective at times, but we are increasingly finding that it takes too much time to actually implement. Instead, I prefer to use pure JavaScript for pre-loading images.

Here are two such preloading methods that work beautifully with all modern browsers.

JavaScript snippet 1

Simply edit and load the path and name of the image you need, which 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>
Copy the code

This method is especially useful for preloading large numbers of images. My gallery website uses this technique to preload more than 50 images. Apply this script to the login page and most gallery images will be preloaded as soon as the user enters the login account.

JavaScript snippet 2

This method is similar to the above method and can also preload any number of images. Add the following script to any Web page and edit it according to 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>
Copy the code

As you can see, you need to create a variable for each Image you load, such as “img1 = new Image();” , and the image source address declaration, such as “img3.src =”.. The/path/to/image – 003. GIF “;” . With this mode, you can load as many images as you need.

We also improved the method. Seal the script in a function and use addLoadEvent () to delay the 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 = "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);Copy the code

Method 3: Use Ajax for preloading

As if the above method isn’t cool enough, let’s look at a way to use Ajax for image preloading. This method uses the DOM to preload not only images, 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 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 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);  

};
Copy the code

The code above preloads’ preload.js’, ‘preload.css’ and ‘preload.png’. The 1000 millisecond timeout is to prevent the script from hanging and causing functional problems on normal pages.

Let’s take a look at how to implement this loading process in 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); 

};
Copy the code

Here, we pre-load the three files by creating three elements in the DOM. As mentioned above, with Ajax, the load file is not applied to the load page.