user3877230
user3877230

Reputation: 458

Load images faster?(PHP, JQuery)

I have a JQuery-Code like this:

var number_images = 5;
var ct = 1;

// Goto previous Picture
$('#changeImageMinus').on('click', function()
{
    if(ct-1>=1 && ct-1<=number_images)
    {
        ct = ct - 1;
        $('.container-bg').css("background-image","url('images/" +  ct + ".png')");
    }
})

// Goto next Picture
$('#changeImagePlus').on('click', function()
{
    if(ct+1>=1 && ct+1<=number_images)
    {
        ct = ct + 1;
        $('.container-bg').css("background-image","url('images/" +  ct + ".png')");
    }
})

I have images named like 1.png, 2.png ... in the folder images/, so i simply load the images back/forward by pressing a "+" or a "-" button. The problem ist that the loading takes really long and i would like to know if there is a possible way to preload all images into a buffer or something like that. I basically want to load the images all before the site openes so that it will show off faster when i switch them. Thank you very much in advance!

Upvotes: 0

Views: 312

Answers (1)

AdamM
AdamM

Reputation: 191

You can do it with JS by using Image class. Create new Image object and set it's src property with path to your picture. Do it for all images before printing page and you should have them preloaded. In this article they describe it (second way).

Just be careful because if you have a lot of pictures it can negatively affect the user experience, especially for the users with slower connection (yes they exist, me for example :D). Imagine that you need to wait few (like 10 or more) seconds for a page to load. The best method in such cases would be preloading the specified amount of images and then loading the rest if needed. The problem of waiting may occure again then but at least user will see your page and not search for some other one :)

Upvotes: 1

Related Questions