Three methods of image preloading and their advantages and disadvantages are analyzed

  • 2020-03-30 04:21:43
  • OfStack

Preloading images is a great way to improve the user experience. Images are pre-loaded into the browser, and visitors can surf your site without a problem and enjoy extremely fast loading. This is great for photo galleries and sites with a high proportion of images, ensuring that images are published quickly and seamlessly, and also helping users to have a better user experience when viewing your content. This article will share three different preloading techniques to enhance your site's performance and availability.

Method 1: preload with CSS and JavaScript

There are many ways to implement preloaded images, including using CSS, JavaScript, and various combinations of the two. These techniques can be used to design solutions according to different design scenarios, which is very efficient.
Simple use of CSS, can easily and efficiently preload 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; } 

By applying these three ID selectors to the (X)HTML element, we can preload the image to the off-screen background using the CSS background attribute. As long as the path of these images remains the same, the browser will use the preloaded (cached) images during rendering when they are invoked elsewhere on the Web page. Simple, efficient, and doesn't require any JavaScript.
Although the method is efficient, there is still room for improvement. Images loaded using 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 to delay preloading until the page is loaded. The code is as follows:


// better image preloading @ <A href="http://perishablepress.com/press/2009/12/28/3-ways-preload-images-css-javascript-ajax/">http://perishablepress.com/press/2009/12/28/3-ways-preload-images-css-javascript-ajax/</A> 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 took the element that used the class selector and set the background attribute 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 in the user's browser? Very simple, the image is not preloaded, when the page calls the image, the normal display.

Method 2: preload using JavaScript only

The above approach is sometimes effective, but we've come to realize that it takes too much time to implement. Instead, I prefer to use pure JavaScript to preload images. Here are two such preloading methods that work nicely on all modern browsers.

JavaScript snippet 1
Simply edit and load the path and name of the required image, which is easy to achieve:


<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> 

This method is especially suitable for preloading a large number of images. My gallery site USES this technique to pre-load more than 50 images. Apply the script to the login page and most of the gallery images will be preloaded as soon as the user enters the login account.

JavaScript snippet 2
This method is similar to the one above 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">
        <!--//--><![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>

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 want.
We have improved the method. Load the script into 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); 

Method 3: preload using Ajax

As if the methods presented above weren't cool enough, here's a way to preload images using Ajax. This method USES the DOM to not only preload 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);   
}; 

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 the normal page.
Now, 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 the DOM to preload the three files. As mentioned above, with Ajax, the load file is not applied to the load page. In this respect, the Ajax approach is superior to JavaScript.

Ok, this article will be introduced here, the three methods to achieve image preloading technology, we have known it, specific which is more efficient, I think friends have seen, then apply to their own projects.


Related articles: