Using CSS, JavaScript, and Ajax to pre-load images, cssajax

Source: Internet
Author: User

Using CSS, JavaScript, and Ajax to pre-load images, cssajax

Pre-loading images is a good way to improve user experience. When images are pre-loaded into the browser, visitors can smoothly surf your website and enjoy extremely fast loading. This is very advantageous for websites with a large proportion of image galleries and images. It ensures fast and seamless publishing of images, it can also help users get a better user experience when browsing the content of your website. This article will share three different pre-loading technologies to enhance the website's performance and availability.

Method 1: implement pre-loading with CSS and JavaScript

There are many ways to implement pre-loading images, including using CSS, JavaScript, and various combinations of the two. These technologies can be used to design corresponding solutions based on different design scenarios, which is very efficient.

With CSS alone, you can easily and efficiently pre-load images. 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; }

Apply the three ID selectors to the (X) HTML element. Then, we can pre-load the image to the background outside the screen through the background attribute of CSS. As long as the paths of these images remain unchanged, when they are called elsewhere on the web page, the browser will use pre-loaded (cached) images during rendering. Simple and efficient, without any JavaScript. Although this method is efficient, there is still room for improvement. The image loaded with this method is 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 pre-loading time until the page loading is complete. 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 the first part of the script, we obtain the elements using the class selector and set the background attribute for it to pre-load 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 cannot run normally in your browser? Very simple. images are not pre-loaded. When the page calls images, they are displayed normally.

Method 2: use JavaScript only for pre-loading

The above method is sometimes very efficient, but we gradually find that it will take too much time in the actual implementation process. On the contrary, I prefer to use pure JavaScript to implement image pre-loading. The following two pre-loading methods are provided, which can work well on all modern browsers.

JavaScript code segment 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>

You only need to simply edit and load the path and name of the image you want. This is easy to implement:

This method is especially suitable for pre-loading a large number of images. My gallery website uses this technology to pre-load more than 50 images. Apply the script to the logon page. Most gallery images are pre-loaded as long as the user enters the Logon account.

JavaScript code segment 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 preceding method. You can also pre-load any number of images. 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 the source Image address Declaration, such as "img3.src = ".. /path/to/image-003.gif ";". Refer to this mode to load any number of images as needed.

We have also improved this method. Encapsulate the script into a function and use addLoadEvent () to delay the pre-loading 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: Use Ajax for pre-loading

The method shown above does not seem cool enough. Now let's look at a method that uses Ajax to implement image pre-loading. This method uses DOM to not only pre-load images, but also pre-load CSS, JavaScript and other related things. The advantage of using Ajax is that loading JavaScript and CSS does 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 response code predefines the response preload.js?##preload.css=and response preload.png ". 1000 milliseconds of timeout is used to prevent the script from being suspended, leading to functional problems on normal pages.

Next, let's take a look at how to use JavaScript to implement the loading process:

window.onload = function() {    setTimeout(function() {        // reference to 

Here, we use DOM to create three elements to implement pre-loading of three files. As mentioned above, with Ajax, file loading will not be applied to page loading. From this point of view, the Ajax method is superior to JavaScript.

The above is all the content of this article. I hope this article will help you in your study or work. I also hope to provide more support to the customer's home!

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.