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 jQuery 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 jQuery to Preload Images with CSS and JavaScript

Using jQuery to Preload Images with CSS and JavaScript








Article Posted On Date : Monday, April 5, 2010


Using jQuery to Preload Images with CSS and JavaScript
Advertisements

If you're a web designer searching for a guide to implementing the most common graphic preloading methods available nowadays, then you've come to the right place. This five-part article series lets you accomplish this task by utilizing either a few basic style sheet properties or the functionality provided by client-side scripting. In this fifth part of the series, we'll employ the jQuery JavaScript library to assist in preloading our images.

Even though the topic seems intimidating and somewhat obscure, preloading images on web pages is a fairly straightforward process that can be mastered with only an average background in CSS and JavaScript. That's all you need, really.

Of course, if you've been a patient reader of the series and already went through all of the parts  previous to this one, then you now have solid knowledge of how to use a combination of CSS and JavaScript to create some simple, yet functional, image preloading mechanisms on your own (X)HTML pages. In the course of those tutorials I demonstrated how to accomplish this with a decent variety of code samples.

To be more specific, I left off the last tutorial showing how to prefetch a set of sample images in the background by using just plain JavaScript, which speaks for itself about the simplicity of this process. However, the trends that rule the world of modern web design say that if something can be done with native JavaScript, it's quite probable that the same results can be obtained using the level of abstraction offered by jQuery. In keeping with this idea, in this last installment of the series, I'm going to demonstrate how to develop a small image prefetching application, which will base all of its functionality on the jQuery library to do its business.

Ready to tackle the final chapter of this hopefully educational journey in preloading images with CSS and JavaScript? Then don't hesitate anymore; click on the link below and jump in!


Using jQuery to Preload Images with CSS and JavaScript - Review: creating an image preloader mechanism with plain JavaScript

(Page 2 of 4 )

As I mentioned, implementing a basic image preloader using plain JavaScript is an extremely simple task. It only requires doing some DOM manipulation and nothing else. The full details of this process were covered in the previous part of the series, but in case you still haven't read that installment, below I listed for you the source code corresponding to this particular example. 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>

As the above code fragment demonstrates, the implementation of a basic image preloading mechanism with JavaScript is a two-step process. It demands, first, the creation of a new image object for each graphic being loaded, and second, filling the object with the image in question, in this case using the "src" attribute. Is there anything simpler to grasp than this approach? I don't think so.

But before you move on, let's analyze the previous script more closely. Obviously, there's plenty of room to improve it and make it slightly more flexible. The first enhancement that comes to my mind is the inclusion of an iterator that allows you to traverse collections of image objects for easier manipulation.

Logically, this can be done using native JavaScript methods and properties, but in this case I'm going to show you how to produce the same result with jQuery. This will not only make the whole preloading process a bit more abstract, but it'll permit you to handle potential errors, at least at a basic level.

To see how I plan to develop this jQuery-based image preloader, click on the link below and read the following section.


If you're ever worked with the jQuery library, you know that it allows developers to perform complex tasks by writing only a few lines of compact code, thanks to its famous fluent interface and its set of convenient methods. Well, I have to admit that creating an image preloader with jQuery isn't the most difficult challenge that can ever be faced, but the following script shows that the library turns this process into a no-brainer. Check it out:

$(document).ready(function () {

var images = ['sample_image1.jpg', 'sample_image2.jpg', 'sample_image3.jpg', 'sample_image4.jpg', 'sample_image5.jpg'];

$(images).each(function(key, value) {

var img = new Image();

$(img)

.attr('src', value)

.error(function (){

alert('Error preloading image ' . value);

})

});

});

That was really easy to code and read, right? As you can see, the implementation of the same image preloader that you saw in the previous segment has been improved considerably thanks to the functionality provided by jQuery. In this case, the library makes it easier to load a variable number of images, and permits you to handle errors in a slightly more graceful way.

So far, so good. At this point you've surely grasped how to create a graphic preloader with jQuery, so the last thing we need to do is include the earlier JavaScript snippet into a sample web page. That's exactly what I'm going to do in the section to come. So click on the link below and read the following lines.


To get this jQuery-based image preloader up and running, the final step we must take is to bind the previous JavaScript code to the structure of a web page. To keep things uncluttered and easy to follow, in this example I'm going to use the same XHTML document shown in other tutorials of this series, which featured the typical header, content and footer sections.

In summary, the finished version of the preloader will look as follows:

<!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 jQuery</title>

<script type="text/javascript" src="jquery-1.3.2.min.js"></script>

<script type="text/javascript">

$(document).ready(function () {

var images = ['sample_image1.jpg', 'sample_image2.jpg', 'sample_image3.jpg', 'sample_image4.jpg', 'sample_image5.jpg'];

$(images).each(function(key, value) {

var img = new Image();

$(img)

.attr('src', value)

.error(function (){

alert('Error preloading image ' . value);

})

});

});

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

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

Done. At this stage, it's safe to say that the image preloader is finally ready to be put into action. So, I suggest that you create your own sample images or simply utilize the ones shown in the first part of the series and give the above script a try on your machine. If you have the chance to use a Firefox extension like Firebug or HTTP Live Headers to examine the set of HTTP requests and headers exchanged between the browser and the web server, you'll see that the preloader works remarkably well.

Final thoughts

Unfortunately, we've come to the end of the series. Nevertheless, the experience has been educational and why not, also fun, since you learned a few useful approaches that can be easily implemented on a web page for preloading images in the background. For obvious reasons, I'd recommend that you use only the ones that don't require you to code additional, non-semantic markup. However, if you feel more comfortable working with JavaScript-based preloaders, make sure they will stick neatly to the rules of progressive enhancement or graceful degradation.






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.