Jump to content

Preloading Images


GerryH
 Share

Recommended Posts

I understand you can preload images with the traditional method;

image1 = new Image();image1.src = "image1.jpg";

but I was wondering if you can preload images in this fashon in an external javascript file such as;

window.onload = Initialize;function Initialize(){   document.getElementById('b1').onmouseover = function(){swapImage('b1', '../images/objsel.jpg', 1)};   document.getElementById('b1').onmouseout  = function(){swapImage('b1', '../images/obj.jpg', 0)};   document.getElementById('b1').onclick = function(){changePage('para', 'b1', '../images/objover.jpg', 'b1')};   ...}function swapImage(id, name, cursor_type){   if (activeBtn == id)	  return;   var x = document.getElementById(id);   x.src = name;   if (cursor_type == '0')	  x.style.cursor = "default";   else		  x.style.cursor = "pointer";	}

and the HTML snippet;

<img class="marginleft" id="b1" src="../images/obj.jpg" alt="Objective" />

.My understanding is the images are loaded automatically when the page loads e.g. the <img> would load the obj.jpg in the body of the document, but as I'm assigning events in the head, would these load the images, or is it just passing it as a string to the function?Thanks!

Link to comment
Share on other sites

Yup. None of that (except the image tag) preloads anything. Those event handlers don't see anything but strings until this statement is actually executed:x.src = name;At that moment, the image will get downloaded (if it is not already cached). This means your first rollover will be annoyingly slow.

Link to comment
Share on other sites

Thanks DD,That's what I thought, the reason I asked is because even with clearing the cache, temp files, etc, I got no delay problems (testing it on a dial-up connection aka 56K), where as before I added the event handlers to the js, there was a very noticable delay in the rollover images.What's really weird, when I reverted back to adding the event handlers to the <img> in the body and eliminated my Initialize script, and clearing the cache, temp files, etc, the image load delay was noticeable again. I could replicate this with all the major browers consistently (except Safari, and Chrome).

<img class="marginleft" id="b1" src="../images/obj.jpg" alt="Objective" onmouseover="swapimage('b1' '../images/objsel.jpg', 1)" onmouseout="swapimage('b1' '../images/obj.jpg', 1)" />

I've tried to debug this with IE8, Firebug, and Opera, yet I can't see any references to the image property in the document. Am I looking at the wrong object?Thanks!

Link to comment
Share on other sites

I'm a bit dense, here. What I think I'm getting is this:The effect was snappy when the rollover code was assigned in your tag.The effect slowed down when you assigned the code in your script.When you moved it back to the tag, it was still slow.That it?Did something else change? Like, did you augment your swap function with the mouse changes somewhere in the middle of all that, or was it always there?Are you preloading now, and has that changed anything?

Link to comment
Share on other sites

Sorry, perhaps I should retake an few English classes at the community college!What I meant to say is when the event handlers are assigned via js, there appears to be no delay on initial rollover (onmouseover image displays without delay), whereas when the mouse events are declared in the tag, the first rollover would momentarially display an "X" as the image loads (as expected).I realize this is totally academic as pre-loading the images is the correct way to go, I just can't really explain what might be different. As a test I'm going to change my mouseover glyph to some hideously large size, and compare load times with and without the js.

Link to comment
Share on other sites

I see. Well, for all I know the interpreter really does anticipate the code and loads the images into cache without being told to. It might vary from browser to browser.FWIW, it is best practice to assign event handlers in your script rather than the tag. Tag assignments essentially create a string that needs to be evaluated. Assigning a function or function reference in your script skips that evaluation step. So much the better if the performance is faster.

Link to comment
Share on other sites

Well debugging IE8 and watching the "Temporary Internet Files" directory during the execution of the script does not automatically pre-load these mouseover images, regardless of js, or tag assignment, so you are absolutely correct about script assignment boosting performance as it loads much faster.One other question I have regarding the document object, and this confuses me coming from a strict C++ background, that I can create a copy of the document object, and create my own array, which I can then dynamically create my own images, which are saved in the browers cache.

function preloadImages() {    var doc=document; 	   if (doc.images)   { 	  if (!doc.ghImg) 		 doc.ghImg = new Array();			  var i;	  var len = doc.ghImg.length;	  var argStr = preloadImages.arguments;			  for (i=0; i < argStr.length; i++)	  {		 if (argStr[i].indexOf('#')!= 0)		 { 			doc.ghImg[len] = new Image; 			doc.ghImg[len++].src = argStr[i];		 }	  }	   }}

Okay, here I've created a copy of the document object and have added my own array object to this instance, and then created image objects as I parse the argStr. This part makes sense, however, how does the browser know of my instance of my new "doc"? This is where I'm lost, as this function loads these images in the browser, and can be referenced without any reference to the doc.ghImg object.I would think my "doc" object would be a completely different from the global "document" object, but this doesn't seem to be the case. If you have any suggestions (aside from where I can place my cranium :) ) it would be very much appriceated!Thanks again for your help!GH

Link to comment
Share on other sites

It's not the case, it doesn't copy the document object, it references it. Outside that function you should be able to refer to document.ghImg and find your image object there as well. All you're really doing is using doc as a shortcut or alias to the document object. It's probably better not to try to copy the document object, that would almost double the memory requirements for Javascript.

Link to comment
Share on other sites

A preload script for images i used ispreload_img.jsfunction MM_preloadImages() { //v3.0var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();var i,j=d.MM_p.length,a=MM_preloadImages.arguments;for(i=0; i<a.length; i++)if (a.indexOf('#')!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a;}}}which is run by a function within pagefunction preload() {MM_preloadImages('media/image1.jpg','media/image2.jpg','media/image3.jpg','media/image4.jpg','media/image5.jpg','media/image6.jpg','media/image7.jpg');}which is initiated bywindow.onload=preload;or<body onload="preload()">Another option is to use a background image, instead of <img> tag.with the background image you can combine the normal image, with an hover image, producing one 50px image, instead of two 25px images. This background image would be displayed within a 25px high element.Then you would use background positioning to move background-image up by 25px to show the hover state image.One image, does both states (normal, hover), so there no delay in loading for a hover state, compared to using two images.Note: you may want to check internet options in IE, and make sure settings for 'Check for newer versions of stored pages' in 'Temporary Internet Files' is not set to 'Every time i visit the webpage', produces delayed hover effect especially in IE6.

Link to comment
Share on other sites

dsonesuk's last comment refers to a thing more generally known as sprites. (Google it for more info.) It's a wonderful technique that saves a lot of HTTP requests and javascript hassles, and it's especially suited to button and icon hovers and other state changes.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...