Best Ways to Preload Image JavaScript with CSS, AJAX

Best Ways to Preload Image JavaScript with CSS, AJAX

Surfing time - is the loading time in other hand - is the big problem to all websites, site owners. And now, it's one of important factor to Google for ranking our URLs. For the big sites have a lot of images, this problem becomes more important cause the visitor's impatience.

If you own these sites and you need a good JavaScript solution, you should practice 3 ways to JavaScript preload images in this JavaScript tutorial. They're so easy and clear to follow, please go to the detailed post-page for instructions and JavaScript codes.


Sampled by © JavaScriptBank.com

Preloadingimages is a great way to improve the user experience. When images arepreloaded in the browser, the visitor can surf around your site andenjoy extremely faster loading times. This is especially beneficial forphoto galleries and other image-heavy sites where you want to deliverthe goods as quickly and seamlessly as possible. Preloading imagesdefinitely helps users without broadband enjoy a better experience whenviewing your content. In this article, we'll explore three differentpreloading techniques to enhance the performance and usability of yoursite.

Method 1: Preloading with CSS and JavaScript

There are many ways to preload images, including methods that rely on CSS, JavaScript, and various combinations thereof. As one of my favorite topics here at Perishable Press, I have covered image preloading numerous times:

Eachof these techniques sort of builds on previous methods and remainsquite effective and suitable for a variety of design scenarios.Thankfully, readers always seem to chime in on these posts withsuggestions and improvements. Recently, Ian Dunn posted an article that improves upon my Better Image Preloading without JavaScript method.

With that method, images are easily and effectively preloaded using the following CSS:

#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 strategically applying preload IDs to existing (X)HTML elements, we can use CSS' backgroundproperty to preload select images off-screen in the background. Then,as long as the paths to these images remains the same when they arereferred to elsewhere in the web page, the browser will use thepreloaded/cached images when rendering the page. Simple, effective, andno JavaScript required.

As effective as thismethod is, however, there is room for improvement. As Ian points out,images that are preloaded using this method will be loaded along withthe other page contents, thereby increasing overall loading time forthe page. To resolve this issue, we can use a little bit of JavaScriptto delay the preloading until after the page has finished loading. This is easily accomplished by applying the CSS background properties using Simon Willison's addLoadEvent() script:

// better image preloading @ http://perishablepress.com/press/2009/12/28/3-ways-preload-images-css-javascript-ajax/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 this script, we are setting up the actual preloading by targeting specific preload elements with background styles that call the various images. Thus, to use this method, you will need to replace the "preload-01", "preload-02", "preload-03", etc., with the IDs that you will be targeting in your markup. Also, for each of the background properties, you will need to replace the "image-01.png", "image-02.png", "image-03.png", etc., with the path and name of your image files. No other editing is required for this technique to work.

Then, in the second part of the script, we are using the addLoadEvent() function to delay execution of our preloader() function until after the page has loaded.

SOwhat happens when JavaScript is not available on the user's browser?Quite simply, the images will not be preloaded and will load as normalwhen called in the web page. This is exactly the sort of unobtrusive,gracefully degrading JavaScript that we really like :)

Method 2: Preloading with JavaScript Only

Aseffective as the previous method happens to be, I generally find it tobe too tedious and time-consuming to actually implement. Instead, Igenerally prefer to preload images using a straight-up slice ofJavaScript. Here are a couple of JavaScript-only preloading methodsthat work beautifully in virtually every modern browser..

JavaScript Method #1

Unobtrusive,gracefully degrading, and easy to implement, simply edit/add the imagepaths/names as needed - no other editing required:

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

Thismethod is especially convenient for preloading large numbers of images.On one of my gallery sites, I use this technique to preload almost 50images. By including this script on the login page as well as internalmoney pages, most of the gallery images are preloaded by the time theuser enters their login credentials. Nice.

JavaScript Method #2

Here'sanother similar method that uses unobtrusive JavaScript to preload anynumber of images. Simply include the following script into any of yourweb pages and edit according to the proceeding 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, each preloaded image requires a variable definition, "img1 = new Image();", as well as a source declaration, "img3.src = "../path/to/image-003.gif";".By replicating the pattern, you can preload as many images asnecessary. Hopefully this is clear - if not, please leave a comment andsomeone will try to help you out.

We can even improve this method a bit by delaying preloading until after the page loads. To do this, we simply wrap the script in a function and use addLoadEvent() to make it work:

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

Ahhh, the joys of JavaScript!

Method 3: Preloading with Ajax

As if all of that weren't cool enough, here is a way to preload images using Ajax. This method was discovered at Of Geeks and letters, and uses the DOM to preload not only images, but CSS, JavaScript, and just about anything else. The main benefit of using Ajax over straight JavaScript is that JavaScript and CSSfiles can be preloaded without their contents affecting the currentpage. For images this is not really an issue, but the method is cleanand effective nonetheless.

window.onload = function() {setTimeout(function() {// XHR to request a JS and a CSSvar 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 imagenew Image().src = "http://domain.tld/preload.png";}, 1000);};

As is, this code will preload three files: "preload.js", "preload.css", and "preload.png". A timeout of 1000ms is also set to prevent the script from hanging and causing issues with normal page functionality.

To wrap things up, let's look at how this preloading session would look written in plain JavaScript:

window.onload = function() {setTimeout(function() {// reference to <head>var head = document.getElementsByTagName('head')[0];// a new CSSvar css = document.createElement('link');css.type = "text/css";css.rel  = "stylesheet";css.href = "http://domain.tld/preload.css";// a new JSvar js  = document.createElement("script");js.type = "text/javascript";js.src  = "http://domain.tld/preload.js";// preload JS and CSShead.appendChild(css);head.appendChild(js);// preload imagenew Image().src = "http://domain.tld/preload.png";}, 1000);};

Here we are preloading our three files upon page load by creating three elements via the DOM. As mentioned in the original article, this method is inferior to the Ajax method in cases where the preloaded file contents should not be applied to the loading page.

Know some triks?

Ilove these preloading tricks so much, I could just squeeze something.If you know of any good preloading tricks, including any improvementsto the techniques shared here, kick start my heart with your wise wordsof preloading wisdom ;)

Source: http://perishablepress.com/press/2009/12/28/3-ways-preload-images-css-javascript-ajax/

Language
Translate this page to English Translate this page to French Translate this page to Vietnamese

Recent articles
20 Best of Beautiful Social Media Icons Sets - p6
Cart66 WordPress eCommerce
The Benefits and Limitations of Reverse Phone Directories
50+ Indispensable JavaScript, jQuery codes for Web Developers
JavaScript Slider Website Showcases
Modules and Namespaces in JavaScript
Eight Awesome JavaScript Applications with Powerful WebGL
Implementing An SEO Reseller Plan without Fear
Professional Logo Design Agency
JavaScript Classical Inheritance


Top view articles
Top 10 Beautiful Christmas Countdown Timers
65 Free JavaScript Photo Gallery Solutions
Using JavaScript to Change Your Web Page Font Size
Top 50 Most Addictive and Popular Facebook mini games
Top 10 Best JavaScript eBooks that Beginners should Learn
50+ Beautiful Resources of HTML Form using CSS and JavaScript
Javascript Countdown Timer redirecting For Your Affiliate Links
Best Free Linux Web Programming Editors
HTML5 Web Workers Multithreading in JavaScript
Top 10 Free Web Chat box Plug-ins and Add-ons


Free JavaScript Tutorials & Articles
at www.JavaScriptBank.com
<center>Trang này sử dụng FRAME nhưng trình duyệt bạn không hỗ trợ. Bạn có thể xem trực tiếp thông qua liên kết <a href="http://www.javascriptbank.com/javascript/article/Best_Ways_to_Preload_Image_JavaScript_with_CSS__AJAX.php">http://www.javascriptbank.com/javascript/article/Best_Ways_to_Preload_Image_JavaScript_with_CSS__AJAX.php</a> </center>