Vyoms OneStopTesting.com - Testing EBooks, Tutorials, Articles, Jobs, Training Institutes etc.
OneStopGate.com - Gate EBooks, Tutorials, Articles, FAQs, Jobs, Training Institutes etc.
OneStopMBA.com - MBA EBooks, Tutorials, Articles, FAQs, Jobs, Training Institutes etc.
OneStopIAS.com - IAS EBooks, Tutorials, Articles, FAQs, Jobs, Training Institutes etc.
OneStopSAP.com - SAP EBooks, Tutorials, Articles, FAQs, Jobs, Training Institutes etc.
OneStopGRE.com - of GRE EBooks, Tutorials, Articles, FAQs, Jobs, Training Institutes etc.
Bookmark and Share Rss Feeds

Using Client-Side Scripting to Preload Images with CSS and JavaScript | Articles | Recent Articles | News Article | Interesting Articles | Technology Articles | Articles On Education | Articles On Corporate | Company Articles | College Articles | Articles on Recession
Sponsored Ads
Hot Jobs
Fresher Jobs
Experienced Jobs
Government Jobs
Walkin Jobs
Placement Section
Company Profiles
Interview Questions
Placement Papers
Resources @ VYOMS
Companies In India
Consultants In India
Colleges In India
Exams In India
Latest Results
Notifications In India
Call Centers In India
Training Institutes In India
Job Communities In India
Courses In India
Jobs by Keyskills
Jobs by Functional Areas
Learn @ VYOMS
GATE Preparation
GRE Preparation
GMAT Preparation
IAS Preparation
SAP Preparation
Testing Preparation
MBA Preparation
News @ VYOMS
Freshers News
Job Articles
Latest News
India News Network
Interview Ebook
Get 30,000+ Interview Questions & Answers in an eBook.
Interview Success Kit - Get Success in Job Interviews
  • 30,000+ Interview Questions
  • Most Questions Answered
  • 5 FREE Bonuses
  • Free Upgrades

VYOMS TOP EMPLOYERS

Wipro Technologies
Tata Consultancy Services
Accenture
IBM
Satyam
Genpact
Cognizant Technologies

Home » Articles » Using Client-Side Scripting to Preload Images with CSS and JavaScript

Using Client-Side Scripting to Preload Images with CSS and JavaScript








Article Posted On Date : Monday, April 5, 2010


Using Client-Side Scripting to Preload Images with CSS and JavaScript
Advertisements

In this fourth part of a series, I demonstrate that preloading a group of images with JavaScript is an easy-to-master process, especially if you already have an intermediate background in manipulating the DOM via client-side scripting. Note that the biggest drawback to the approach is its dependence on JavaScript to do its thing; you should keep this in mind when implementing this type of image preloading mechanism on your own web pages.

Usually, the term "eager loading" is used to refer to a well-known design pattern, often implemented in desktop and web-based applications. As its name implies, the pattern permits a given program to load a specific resource, be it a database result set, a class instance or an XML file in anticipation of need, regardless of whether the resource is used during the program's execution.

While at first sight eager loading seems to be pretty pointless, under certain conditions it can be useful for improving the performance of an application. A good example that shows the benefits of using eager loading is a web program that displays blog entries and comments: apart from pulling records from an "entries" database table, the program could eventually "prefetch" in the background all of the comments associated with each entry. Get the point? I bet you do.

Considering the previous example, you may feel inclined to think that eager loading can only be applied on the server side. Actually, the same concept can be used when rendering web pages, and more specifically when displaying online images. In fact, today there are some popular techniques that allow you to preload images easily, either with CSS or JavaScript, which lets users see them with no visible delay.

To illustrate how to use eager loading for showing images on screen, in previous installments of this series I went through the development of a few basic methods for preloading a set of sample graphics. I made clever use of the "background-image" CSS property.

While it's valid to point out that one group of these methods required the coding of additional markup, which doesn't speak very well about their efficiency, all of them relied on the functionality of CSS to work properly. This doesn't mean, however, that style sheets are the only way to preload images in the background. In fact, it's possible to produce similar results using plain JavaScript.

Therefore, in this fourth chapter of the series I'm going explain how to use some native JavaScript code to implement a rudimentary, yet functional, image preloading mechanism. Ready to learn the full details? Then let's get started!


Undoubtedly, one of the most effective techniques to use for preloading sets of images in the background takes advantage of the "background-image" CSS property to hook the images to existing containers within a web page. This approach permits you to achieve the desired goal without having to write portions of non-semantic markup. The following example, which was developed in the previous installment of the series, shows how to implement this in a few simple steps:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<title>Preloading images using CSS (no additional markup is required)</title>

<style type="text/css">

body {

padding: 0;

margin: 0;

background: #000080;

font: 1em Arial, Helvetica, sans-serif;

color: #000;

}

#wrapper {

width: 960px;

margin: 0 auto;

background: #eee;

}

/* the header, content and footer containers are used as hooks to preload images */

#header {

padding: 10px;

background: url("sample_image1.jpg") -9999px -9999px no-repeat;

}

#content {

padding: 10px;

background: url("sample_image2.jpg") -9999px -9999px no-repeat;

}

#footer {

padding: 10px;

background: url("sample_image3.jpg") -9999px -9999px no-repeat;

}

/* sample images */

img {

padding: 10px;

background: #fff;

border: 1px solid #ddd;

}

</style>

</head>

<body>

<div id="wrapper">

<div id="header">

<h1>Preloading images using CSS (no additional markup is required)</h1>

<h2>Header section</h2>

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse auctor commodo risus, et ultrices sapien vestibulum non. Maecenas scelerisque quam a nulla mattis tincidunt. Etiam massa libero, pharetra vel laoreet et, ultrices non leo. Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>

</div>

<div id="content">

<h2>Main content section</h2>

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse auctor commodo risus, et ultrices sapien vestibulum non. Maecenas scelerisque quam a nulla mattis tincidunt. Etiam massa libero, pharetra vel laoreet et, ultrices non leo. Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>

<p><img src="sample_image1.jpg" width="400" height="300" alt="Sample Image 1" /></p>

<p><img src="sample_image2.jpg" width="400" height="300" alt="Sample Image 2" /></p>

<p><img src="sample_image3.jpg" width="400" height="300" alt="Sample Image 3" /></p>

</div>

<div id="footer">

<h2>Footer section</h2>

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse auctor commodo risus, et ultrices sapien vestibulum non. Maecenas scelerisque quam a nulla mattis tincidunt. Etiam massa libero, pharetra vel laoreet et, ultrices non leo. Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>

</div>

</div>

</body>

</html>

From the above example, it's clear to see that when used intelligently, the "background-image" property can be very helpful for preloading multiple images behind the scenes. In this case, only three graphics have been attached to different sections of the web page, but naturally it's possible to preload a few more, depending on your specific needs.

So far, so good. Now that you've learned how the prior approach works, it's time to explore other preloading methods, so you can choose the one that best fits your requirements. Thus, in the following section I'm going to demonstrate how to create a simple prefetching method similar to the one that you just saw, but this time using some basic JavaScript.

To learn more about how this will be done, click on the link below and read the lines to come.


I don't want to sound arrogant, but preloading images with JavaScript is a ridiculously simple task. Essentially, the process requires that you first create an image container in memory, and then fill it with the loaded image. Of course, my words must be backed up by functional code, so below I've created a short JavaScript snippet that will preload in the background a set of five images. Take a look at it:

<script type="text/javascript">

// check to see if the browser accepts images and understands the DOM

if (document.images && document.getElementById && document.getElementsByTagName) {

// preload images

var image1 = new Image();

image1.setAttribute('src', 'sample_image1.jpg');

var image2 = new Image();

image2.setAttribute('src', 'sample_image2.jpg');

var image3 = new Image();

image3.setAttribute('src', 'sample_image3.jpg');

var image4 = new Image();

image4.setAttribute('src', 'sample_image4.jpg');

var image5 = new Image();

image5.setAttribute('src', 'sample_image5.jpg');

}

</script>

Didn't I tell you that preloading pictures with JavaScript was a breeze? Well, this simple script shows that in a nutshell. As you can see, it simply requests the pertinent images via the "src" attribute provided by the DOM and nothing else. Needless to say, the snippet should be always included on top of the web page, so all of the images will be available to be displayed afterward.

All right, having demonstrated how to implement a trivial preloading mechanism using only plain JavaScript, the next step is to include the preloader in an XHTML document, so you can test it and introduce your own improvements. That's exactly what I'm going to do in the last segment of the tutorial, so click on the link below and keep reading.


If you're anything like me, you want to see for yourself if the image preloader developed in the preceding section really functions as expected. Below I coded a web page that includes this simple JavaScript-based mechanism, so you can give it a try on your own browser. Here it is:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<title>Preloading images using plain JavaScript</title>

<script type="text/javascript">

// check to see if the browser accepts images and understands the DOM

if (document.images && document.getElementById && document.getElementsByTagName) {

// preload images

var image1 = new Image();

image1.setAttribute('src', 'sample_image1.jpg');

var image2 = new Image();

image2.setAttribute('src', 'sample_image2.jpg');

var image3 = new Image();

image3.setAttribute('src', 'sample_image3.jpg');

var image4 = new Image();

image4.setAttribute('src', 'sample_image4.jpg');

var image5 = new Image();

image5.setAttribute('src', 'sample_image5.jpg');

}

</script>

<style type="text/css">

body {

padding: 0;

margin: 0;

background: #000080;

font: 1em Arial, Helvetica, sans-serif;

color: #000;

}

/* main containers */

#wrapper {

width: 960px;

margin: 0 auto;

background: #eee;

}

#header, #content, #footer {

padding: 30px;

}

/* sample images */

img {

padding: 10px;

background: #fff;

border: 1px solid #ddd;

}

</style>

</head>

<body>

<div id="wrapper">

<div id="header">

<h1>Preloading images using plain JavaScript</h1>

<h2>Header section</h2>

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse auctor commodo risus, et ultrices sapien vestibulum non. Maecenas scelerisque quam a nulla mattis tincidunt. Etiam massa libero, pharetra vel laoreet et, ultrices non leo. Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>

</div>

<div id="content">

<h2>Main content section</h2>

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse auctor commodo risus, et ultrices sapien vestibulum non. Maecenas scelerisque quam a nulla mattis tincidunt. Etiam massa libero, pharetra vel laoreet et, ultrices non leo. Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>

<p><img src="sample_image1.jpg" width="400" height="300" alt="Sample Image 1" /></p>

<p><img src="sample_image2.jpg" width="400" height="300" alt="Sample Image 2" /></p>

<p><img src="sample_image3.jpg" width="400" height="300" alt="Sample Image 3" /></p>

<p><img src="sample_image4.jpg" width="400" height="300" alt="Sample Image 4" /></p>

<p><img src="sample_image5.jpg" width="400" height="300" alt="Sample Image 5" /></p>

</div>

<div id="footer">

<h2>Footer section</h2>

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse auctor commodo risus, et ultrices sapien vestibulum non. Maecenas scelerisque quam a nulla mattis tincidunt. Etiam massa libero, pharetra vel laoreet et, ultrices non leo. Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>

</div>

</div>

</body>

</html>

Mission accomplished. At this point, the above image preloader is not only fully functional, but can easily be customized for prefetching any number of graphics. Despite these shining advantages, this method naturally suffers from the same problems of any JavaScript application: it can be turned off on the browser. I suggest you use it with caution, or even switch over to a CSS-based implementation.

Final thoughts

In this fourth part of the series, I demonstrated that preloading a group of images with JavaScript is an easy process that can be mastered with minor effort, especially if you already have an intermediate background in manipulating the DOM via client-side scripting. On the other hand, the biggest drawback of the approach shown before is its strong dependency on JavaScript to do its thing, so you should take this issue into account when implementing this type of image prefetching mechanism on your web pages.

Of course, if it's feasible to preload graphics in the background using plain JavaScript, this implies that the same task can be performed with jQuery as well. Therefore, the last part of the series will focus on explaining how to accomplish this with the popular JavaScript library.






Sponsored Ads



Interview Questions
HR Interview Questions
Testing Interview Questions
SAP Interview Questions
Business Intelligence Interview Questions
Call Center Interview Questions

Databases

Clipper Interview Questions
DBA Interview Questions
Firebird Interview Questions
Hierarchical Interview Questions
Informix Interview Questions
Microsoft Access Interview Questions
MS SqlServer Interview Questions
MYSQL Interview Questions
Network Interview Questions
Object Relational Interview Questions
PL/SQL Interview Questions
PostgreSQL Interview Questions
Progress Interview Questions
Relational Interview Questions
SQL Interview Questions
SQL Server Interview Questions
Stored Procedures Interview Questions
Sybase Interview Questions
Teradata Interview Questions

Microsof Technologies

.Net Database Interview Questions
.Net Deployement Interview Questions
ADO.NET Interview Questions
ADO.NET 2.0 Interview Questions
Architecture Interview Questions
ASP Interview Questions
ASP.NET Interview Questions
ASP.NET 2.0 Interview Questions
C# Interview Questions
Csharp Interview Questions
DataGrid Interview Questions
DotNet Interview Questions
Microsoft Basics Interview Questions
Microsoft.NET Interview Questions
Microsoft.NET 2.0 Interview Questions
Share Point Interview Questions
Silverlight Interview Questions
VB.NET Interview Questions
VC++ Interview Questions
Visual Basic Interview Questions

Java / J2EE

Applet Interview Questions
Core Java Interview Questions
Eclipse Interview Questions
EJB Interview Questions
Hibernate Interview Questions
J2ME Interview Questions
J2SE Interview Questions
Java Interview Questions
Java Beans Interview Questions
Java Patterns Interview Questions
Java Security Interview Questions
Java Swing Interview Questions
JBOSS Interview Questions
JDBC Interview Questions
JMS Interview Questions
JSF Interview Questions
JSP Interview Questions
RMI Interview Questions
Servlet Interview Questions
Socket Programming Interview Questions
Springs Interview Questions
Struts Interview Questions
Web Sphere Interview Questions

Programming Languages

C Interview Questions
C++ Interview Questions
CGI Interview Questions
Delphi Interview Questions
Fortran Interview Questions
ILU Interview Questions
LISP Interview Questions
Pascal Interview Questions
Perl Interview Questions
PHP Interview Questions
Ruby Interview Questions
Signature Interview Questions
UML Interview Questions
VBA Interview Questions
Windows Interview Questions
Mainframe Interview Questions


Copyright © 2001-2025 Vyoms.com. All Rights Reserved. Home | About Us | Advertise With Vyoms.com | Jobs | Contact Us | Feedback | Link to Us | Privacy Policy | Terms & Conditions
Placement Papers | Get Your Free Website | IAS Preparation | C++ Interview Questions | C Interview Questions | Report a Bug | Romantic Shayari | CAT 2025

Fresher Jobs | Experienced Jobs | Government Jobs | Walkin Jobs | Company Profiles | Interview Questions | Placement Papers | Companies In India | Consultants In India | Colleges In India | Exams In India | Latest Results | Notifications In India | Call Centers In India | Training Institutes In India | Job Communities In India | Courses In India | Jobs by Keyskills | Jobs by Functional Areas

Testing Articles | Testing Books | Testing Certifications | Testing FAQs | Testing Downloads | Testing Interview Questions | Testing Jobs | Testing Training Institutes

Gate Articles | Gate Books | Gate Colleges | Gate Downloads | Gate Faqs | Gate Jobs | Gate News | Gate Sample Papers | Gate Training Institutes

MBA Articles | MBA Books | MBA Case Studies | MBA Business Schools | MBA Current Affairs | MBA Downloads | MBA Events | MBA Notifications | MBA FAQs | MBA Jobs
MBA Job Consultants | MBA News | MBA Results | MBA Courses | MBA Sample Papers | MBA Interview Questions | MBA Training Institutes

GRE Articles | GRE Books | GRE Colleges | GRE Downloads | GRE Events | GRE FAQs | GRE News | GRE Training Institutes | GRE Sample Papers

IAS Articles | IAS Books | IAS Current Affairs | IAS Downloads | IAS Events | IAS FAQs | IAS News | IAS Notifications | IAS UPSC Jobs | IAS Previous Question Papers
IAS Results | IAS Sample Papers | IAS Interview Questions | IAS Training Institutes | IAS Toppers Interview

SAP Articles | SAP Books | SAP Certifications | SAP Companies | SAP Study Materials | SAP Events | SAP FAQs | SAP Jobs | SAP Job Consultants
SAP Links | SAP News | SAP Sample Papers | SAP Interview Questions | SAP Training Institutes |


Copyright ©2001-2025 Vyoms.com, All Rights Reserved.
Disclaimer: VYOMS.com has taken all reasonable steps to ensure that information on this site is authentic. Applicants are advised to research bonafides of advertisers independently. VYOMS.com shall not have any responsibility in this regard.