Home > Web Front-end > JS Tutorial > Three major methods to achieve image preloading using CSS, JavaScript and Ajax

Three major methods to achieve image preloading using CSS, JavaScript and Ajax

大家讲道理
Release: 2017-01-24 16:11:08
Original
1213 people have browsed it

Preloading images is a great way to improve user experience. With images pre-loaded into the browser, visitors can smoothly surf your site and enjoy blazingly fast loading times. This is very beneficial for image galleries and websites where images take up a large proportion. It ensures that images are published quickly and seamlessly, and it also helps users get a better user experience when browsing your website content. This article will share three different preloading techniques to enhance website performance and usability.

Method 1: Use CSS and JavaScript to implement preloading

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

Simply use CSS to preload images easily and efficiently. 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; }
Copy after login

Apply these three ID selectors to the (X)HTML element, and we can use CSS The background property preloads the image onto an off-screen background. As long as the paths to these images remain the same, the browser will use the 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 using this method will be 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 preloading time 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);
Copy after login

In the first part of the script, we get the element using the class selector and set the background attribute for it to preload 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 doesn't run properly in the user's browser? It's very simple. The image will not be preloaded. When the page calls the image, it will be displayed normally.

Method 2: Only use JavaScript to implement preloading

The above method is indeed very efficient sometimes, but we gradually found that it consumes too much time in the actual implementation process. Instead, I prefer to use pure JavaScript for image preloading. Below 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>
Copy after login

Just Simple Just edit and load the path and name of the required image, which is easy to implement:

This method is especially suitable for preloading a large number of images. My gallery website uses this technology to preload over 50 images. Apply this script to the login page and most of the gallery images will be preloaded as soon as the user enters their login ID.

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>
Copy after login

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

As you can see, each time you load an image, you need to create a variable, such as "img1 = new Image();", and declare the image source address, such as "img3.src = "../path/to /image-003.gif";". Using this pattern, you can load as many images as you need.

We have improved this method. Wrap this script into a function and use addLoadEvent() to delay the preloading 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 != &#39;function&#39;) {
                window.onload = func;
        } else {
                window.onload = function() {                        if (oldonload) {
                                oldonload();
                        }
                        func();
                }
        }
}
addLoadEvent(preloader);
Copy after login
Method 3: Use Ajax to implement preloading

The method given above does not seem cool enough, so now let’s look at a method to use Ajax to implement image preloading . This method uses DOM to not only preload images, but also preload 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. 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(&#39;GET&#39;, &#39;http://domain.tld/preload.js&#39;);
                xhr.send(&#39;&#39;);
                xhr = new XMLHttpRequest();
                xhr.open(&#39;GET&#39;, &#39;http://domain.tld/preload.css&#39;);
                xhr.send(&#39;&#39;);                // preload image                new Image().src = "http://domain.tld/preload.png";
        }, 1000);
};
Copy after login

The above code preloads "preload.js", "preload.css" and "preload .png". The 1000 millisecond timeout is to prevent the script from hanging and causing functional issues with normal pages.

Next, let’s see how to use JavaScript to implement the loading process:


window.onload = function() {
        setTimeout(function() {                // reference to <head>                var head = document.getElementsByTagName(&#39;head&#39;)[0];                // a new CSS                var css = document.createElement(&#39;link&#39;);
                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 after login
Here, we create three through DOM Element to implement preloading of three files. As mentioned above, with Ajax, loading files is not applied to the loading page. From this point of view, Ajax methods are superior to JavaScript.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template