Three ways to preload images with CSS, JavaScript, and Ajax

Source: Internet
Author: User
Tags cdata tld

Original: 3 Ways to preload Images with CSS, JavaScript, or Ajax

Three methods for image preloading using CSS, JavaScript and Ajax

Preloading a picture is a great way to improve the user experience. The images are preloaded in the browser, and visitors can surf the site smoothly and enjoy extremely fast loading speeds . This is good for a large proportion of the image galleries and images, which ensures that the images are released quickly and seamlessly, and help users get a better user experience when browsing the content of your site. This article will share three different preloaded technologies to enhance the performance and usability of your website.

method One: Pre-load with CSS and JavaScript

There are many ways to implement preloaded images, including the use of CSS, JavaScript, and a combination of both. These technologies can be designed according to different design scenarios corresponding solutions, very efficient.

Simply using CSS, you can preload images easily and efficiently, with the following code:

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

Applying the three ID selectors to the (X) HTML element, we can preload the picture onto the offscreen background through the background property of the CSS. As long as the paths to these pictures remain the same, when they are called elsewhere on the Web page, the browser uses the preloaded (cached) picture during the rendering process. simple and efficient, no JavaScript required.

Although this method is efficient, there is still room for improvement. Images loaded with this method are loaded with other contents of the page, increasing the overall load time of the page. To solve this problem, we have added some JavaScript code to postpone the preload until the page has finished loading. 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) {varOldonload =window.onload; if(typeofWindow.onload! ='function') {window.onload=func; } Else{window.onload=function () {if(oldonload) {oldonload ();          } func ();  }}} addloadevent (Preloader); 

In the first part of the script, we get the elements that use the class selector and set the background property for them to preload the different pictures.

In the second part of the script, we use the addloadevent () function to delay the load time of the Preloader () function until the page has finished loading.

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

method Two: Use only JavaScript for preload

The above method is sometimes very efficient, but we gradually find that it takes too much time in the actual implementation process . Instead, I prefer to use pure JavaScript to get the picture preloaded. Here are two of these preload methods, which can work beautifully on all modern browsers.

JavaScript code Snippet 1

Simply edit and load the path and name of the desired picture, which is easy to implement:

<divclass="Hidden"> <script type="Text/javascript"> <!--//--><! [Cdata[//><!--            varImages =NewArray () function preload () { for(i =0; i < preload.arguments.length; i++) {Images[i]=NewImage () 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 useful for preloading a large number of images. My gallery site uses this technology to preload more than 50 images. Apply the 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

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

<divclass="Hidden"> <script type="Text/javascript"> <!--//--><! [Cdata[//><!--            if(document.images) {IMG1=NewImage (); Img2=NewImage (); IMG3=NewImage (); 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, each loaded image needs to create a variable, such as "IMG1 = new Image ();", and a picture source address declaration, such as "IMG3.SRC =". /path/to/image-003.gif ";". With this mode, you can load as many images as you need.

We have also made improvements to this approach. Wrap the script into a function and use addloadevent () to defer the preload until the page has finished loading.

function Preloader () {if(document.images) {varIMG1 =NewImage (); varImg2 =NewImage (); varIMG3 =NewImage (); 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) {varOldonload =window.onload; if(typeofWindow.onload! ='function') {window.onload=func; } Else{window.onload=function () {if(oldonload) {oldonload ();          } func ();  }}} addloadevent (Preloader); 

Method Three: Using Ajax to implement pre-loading

The method shown above does not seem cool enough, so now let's look at a way to use Ajax to implement picture preloading. The method uses the DOM, not just preloaded images, but also pre-loading CSS, JavaScript and other related things. using AJAX, rather than using JavaScript directly, is advantageous in 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        varXHR =NewXMLHttpRequest (); Xhr.open ('GET','Http://domain.tld/preload.js'); Xhr.send ("'); XHR=NewXMLHttpRequest (); Xhr.open ('GET','Http://domain.tld/preload.css'); Xhr.send ("'); //preload Image        NewImage (). src ="Http://domain.tld/preload.png"; },  +);  }; 

The above code preloaded "Preload.js", "Preload.css", and "Preload.png". A 1000-millisecond timeout is intended to prevent the script from suspending, causing a functional problem on the normal page.

Let's look at how JavaScript can be used to implement the loading process:

Window.onload =function () {setTimeout () (function () {//reference to         varHead = document.getElementsByTagName ('Head')[0]; //a new CSS        varCSS = document.createelement ('Link'); Css.type="Text/css"; Css.rel="stylesheet"; Css.href="Http://domain.tld/preload.css"; //a new JS        varJS = document.createelement ("Script"); Js.type="Text/javascript"; JS.SRC="Http://domain.tld/preload.js"; //preload JS and CSShead.appendchild (CSS);            Head.appendchild (JS); //preload Image        NewImage (). src ="Http://domain.tld/preload.png"; },  +);  }; 

Here, we create three elements through the DOM to achieve the preload of three files. As mentioned above, with Ajax, the load file is not applied to the loading page. From this point of view, the AJAX approach is superior to JavaScript.

Three ways to preload images with CSS, JavaScript, and Ajax

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.