0

Hi I have a project in which one of the pages has a gallery. Something like that:

 <div id="gallery" class="sections">
        <img src="Images/Image1.jpg" class="thumbnails">
        <img src="Images/Image2.jpg" class="thumbnails">
        <img src="Images/Image3.jpg" class="thumbnails">
        etc...
 </div>

I would like to preload these images so that when you access the gallery page they are already loaded. I know you can do this by using javascript. Something along the lines of:

var myImage = new Image();
myImage1.src = "Images/Image1.jpg";
etc...

What I am unsure about is the next step. Do I remove the src from the html and add an id, like so:

 <div id="gallery" class="sections">
        <img id="image1" class="thumbnails">
        <img id="image2" class="thumbnails">
        <img id="image3" class="thumbnails">
        etc...
 </div>

and then do something like that:

$('#image1').append(myImage1);

This hasn't worked... I have also tried:

$('#image1').attr('src','Images/Image1.jpg');

And that hasn't worked either.

I have had a look around and there are plenty of tutorials about how to make a function that preloads your images etc... but I am not quite there yet. I just would like to know how to do it on a one by one basis for now and then maybe create a function. Thanks.

2
  • Possible duplicate of Preloading images with jQuery Commented May 5, 2017 at 13:38
  • I am not looking for a function to do this. I just would like to know how to do it with one image for now as I am struggling. Thanks Commented May 5, 2017 at 13:40

1 Answer 1

1

They are many function to do that Images are loaded in the DOM when the page is open, but not visibles. Then, when you want show them (On click, on a slider, ...), no load time !

function preload(arrayOfImages) {
    $(arrayOfImages).each(function(){
        $('<img/>')[0].src = this;
        // Alternatively you could use:
        // (new Image()).src = this;
    });
}

// Use your function with all your image path

preload([
    'img/imageName.jpg',
    'img/anotherOne.jpg',
    'img/blahblahblah.jpg'
]);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.