Ryan
Ryan

Reputation: 257

Forcing images to fully load

I am fairly new to web development, so please excuse my ignorance. I'm working on a page that generates color swatches which are just small sections of high resolution images. There are up to 70 of these swatches being generated at a single time. My problem is that I can't get the images to fully show up on the first try, I have to call the function again to get the images to fully load. If I set up a function that makes my swatches visible upon loading (I'm using JQuery's .load) it never triggers, I'm assuming because it never actually loads. Is there some way to force a full load of pages with a lot of content?

function showswatches(section, xmlHttpObj){
    for(i=0;i<xmlHttpObj.length;i++){
        if(xmlHttpObj[i].getElementsByTagName('section')[0].childNodes[0].nodeValue == section){
            $('#swatches').html();
            var colors = xmlHttpObj[i].getElementsByTagName('color');
            for(j=0;j<colors.length;j++){
                $('#swatches').append('<div class="swatch">');
                $('#swatches').append('<img src='+colors[j].childNodes[0].nodeValue+'>');
                $('#swatches').append('</div>');
            }
        }
    }
}

Upvotes: 0

Views: 383

Answers (1)

Lix
Lix

Reputation: 47986

I can give you two options -


First option -

Add a .load() handler to each image and only display the image once it has fully loaded (in the mean time you could possible display a loader of sorts). If you give all your images the same class you cat attach the event to all of them at once. For example, if all of your <img> elements contain the preloadImg class, and you place a small loader element in your swatch container div, you could create a handler like this -

$('img.preloadImg').on('load',function(){
  $(this).parent().find('loader').hide(); // hide loader
  $(this).show();  // images initially hidden
});

Second option -

You could preload your swatches using JavaScript so that they start loading before your entire document is loaded and jQuery fires the document.ready callback. For this you can simply create an array of JavaScript Image() objects and give each one the appropriate src property.

var imagePaths = ['swatch1.png','swatch2.png','swatch3.png'];
var imageLoader = new Array();
for(var i=0;i<imagePaths.length;i++){
  var img = new Image();
  img.src = imagePaths[i];
  imageLoader.push(img);
}

As soon as you create the Image() object and give it a src property, the image will start loading and this will possibly lessen your loading time becuase as I said before, the images will start loading as soon as JavaScript is available - before jQuery has loaded and even before your full HTML content is loaded.

Upvotes: 1

Related Questions