jQuery - How to preload all images contained within a div.

brianmfalls
brianmfalls used Ask the Experts™
on
I found an question similar on the jQuery site, but it hadn't received any attention.  (jQuery Question)

I know that it is possible to loop through all of the images contained with a div with a specific id by using jQuery's .each() function.  I found an image preload script here, which is shown below.

Has anyone done something where, using document.getElementById() to find the div and .each() to loop through and preload all of the images contained within said div?  Can you share your code if you have?  I'd love to learn how it's done.  Thanks in advance!
(function($) {
	var cache = [];
	// Arguments are image paths relative to the current page.
	$.preLoadImages = function() {
		var args_len = arguments.length;
		for (var i = args_len; i--;) {
			var cacheImage = document.createElement('img');
			cacheImage.src = arguments[i];
			cache.push(cacheImage); } }
})(jQuery)

jQuery.preLoadImages("imageName.jpg", "/path/imageName.jpg");

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
try this one
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<script type="text/javascript" src="jquery-1.4.2.min.js"></script>
	<script>
		(function($) {
		var cache = [];
		// Arguments are image paths relative to the current page.
		$.preLoadImages = function() {
			var args_len = arguments.length;
			for (var i = args_len; i--;) {
				var cacheImage = document.createElement('img');
				cacheImage.src = arguments[i];
				cache.push(cacheImage); } }
			})(jQuery)

		

		$(document).ready(function(){
			$("#imgContainer img").each(function(){
				jQuery.preLoadImages($(this).attr("src"));
			});
		});

	</script>
</HEAD>

<BODY BGCOLOR="#FFFFFF">
	<div id="imgContainer">
		<img src="3445879840_7ca4b491e9.jpg"> <br>
		<img src="3445879840_7ca4b491e9_m.jpg"> <br>
		<img src="3449388113_71a06b8548.jpg"> <br>
		<img src="3449388113_71a06b8548_m.jpg"> <br>
	</div>
</BODY>
</HTML>

Open in new window

Author

Commented:
It isn't throwing errors in the console, but it didn't change the page as I had expected.  The change I expected may be due to other factors.  How can I verify whether or not the script worked in order to close the question and to award you the points?
well, for a script of this small size, it is very difficult to know if the script worked as expected.

you can check in the debugger of your browser to be sure about it.

Author

Commented:
Excellent work friend.  Thank you.
thanks for the points

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial