views:

48

answers:

1

Hello Stack Overflow!

I currently have a mind boggling error. I am using the .load function in jQuery to load images for a slideshow and getting a bunch of errors below by img tag that i am importing the url to. I have done my best to demonstrate my function and markup below. I do not get an error in any modern browsers but IE gives me errors

     $('a').click(function(e){
    $(trainFull).fadeOut(400, function(){
         jQuery(trainFull[0]).load('http://img.jpg", function(){
          jQuery(this).hide().attr('src', 'http://img.jpg").fadeIn(400);
   });



<img alt="Train Full" src="http://img.jpg" ">
<img xmlns="http://www.w3.org/1999/xhtml"&gt;�����JFIF���d�d�����Ducky�����(�����Adobe�d���������--etc, etc, etc/>
+1  A: 

If I understand you correctly, you're trying to pre-load the image using jQuery's XMLHttpRequest wrapper (load()). This is... unlikely to work well.

What you're seeing is IE trying to interpret binary image data as text (with predictably poor results), jQuery trying to stuff them into your <img> element, and IE trying to display them. While this probably does manage to pre-cache the image, it's the wrong tool for the job... and as you've demonstrated, a tool that can fail badly.

Fortunately, there are easier ways. Most browsers provide built-in support for loading images and notifying a script when they have loaded. For instance:

$('<img />') // detached image, used to pre-load
    .attr('src', 'http://img.jpg') // tell it which image to load
    .load(function() // attach a callback to inform us when it's loaded
    {
      // within the callback, "this" refers to the temporary image element
      // that has just finished loading its source

      // now that the image is in the cache,
      $(trainFull[0])
        .attr('src', this.src) // let our on-page image display it
        .fadeIn(400); // and show that
    });

If you want to learn more about this, I recommend starting with: jQuery ajax images preload.

Shog9
Thanks shog9. I now know exactly how .load() works and understand my error. Thanks again you helped immensely!
jnolte