John John - 2 months ago 5x
HTML Question

How to load an onScroll background image before user scrolls to them?

I'm changing background of a div when the user scrolls to the end of that div. Since its a fixed background, I am not using HTML

tag, instead I am using the CSS
. With the following
function, it successfully changes the background when i need it, and reverts back when user scrolls back to top.

function transimg(divid,imgurl1,imgurl2) {
var st = $(this).scrollTop();
var dist = $(divid).offset().top - 50;

if(st > dist) {
$(divid).css("background-image", "url(" + imgurl1 +")");
$(divid).css("background-image", "url(" + imgurl2 +")");

My Question is:

Obviously this loads the image when user scrolls to that offset. Which makes it slow when i host the site and a user has slow connection. So i need the 2nd image to be loaded when the page starts loading. Kind of the opposite of Lazy Load. How can i achieve this ?

I really don't want to use any plugins.

Any help is appreciated, thanks in advance !


You can load them in the before body is load. (Add the script at the end of your body).

Explanation: When you create an Image and set is the src property the image file download to your browser.

var images = ['img1', 'img2'];
for (var i = 0; i < images.length; i++) {
  var img = new Image();
  img.src = images[i];