0

In my wordpress site i am using a quite simple jQuery piece of code:

jQuery(".first-sq").mouseenter(function(){
      jQuery(".first-sq img").attr('srcset', '/wp-content/uploads/2017/01/MachineLearning_hoverx2.png');
 })
 jQuery(".first-sq").mouseleave(function(){
   jQuery(".first-sq img").attr('srcset' , '/wp-content/uploads/2017/01/MachineLearningx2.png');
 })

Now the code works but the problem is when mouseenter called it takes some time for the image to load, and you can see it being loaded. or in other words, the image revealed in portions. Is there a way to load all the images the document might use ,when document load, so when in situations like my mouseenter the image will show immediately and wont have to load?

yariv bar
  • 936
  • 3
  • 20
  • 39
  • 2
    Preload the images, check this [question](http://stackoverflow.com/questions/476679/preloading-images-with-jquery) for answers on how to do this – George Feb 22 '17 at 11:03
  • 1
    Search engine of your choice -> javascript image preload – Andreas Feb 22 '17 at 11:03
  • You can preload images using JavaScript, but a better way is to combine both images into a single one, set is as `background-image` of a `div` and shift the position. Keyword: `css sprites` –  Feb 22 '17 at 11:03
  • Why don't you use jQuery onload function to load the images and then on mouseenter just change the display style to none / block ? – Rohan Veer Feb 22 '17 at 11:04

2 Answers2

0

You could achieve this by preload images. Try something like that:

$(document).ready(function () {
  $('<img src="/wp-content/uploads/2017/01/MachineLearning_hoverx2.png">');
  $('<img src="/wp-content/uploads/2017/01/MachineLearningx2.png">');
});
Przemek
  • 123
  • 3
0

Copy of this

function preload(arrayOfImages) {
    $(arrayOfImages).each(function(){
        $('<img/>')[0].src = this;
    });
}

// Usage:
preload([
    'img/img1.jpg'
]);
Community
  • 1
  • 1
Malcolm Vaz
  • 131
  • 5
  • Please don't [plagiarise answers](http://stackoverflow.com/a/476681/519413). If you reference another answer at least leave the original author a credit. You can also vote to close the question as a duplicate if you feel it's warranted, which would seem to be the case here – Rory McCrossan Feb 22 '17 at 11:12
  • I did post it as a copy with a link ...:| I just didn't like the blah blah so I removed that...And I was unaware about the duplicate thing. – Malcolm Vaz Feb 22 '17 at 11:16
  • No problem, just thought I'd let you know for future reference – Rory McCrossan Feb 22 '17 at 11:17