简体   繁体   中英

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 <img> tag, instead I am using the CSS background-image: . With the following JavaScript function, it successfully changes the background when i need it, and reverts back when user scrolls back to top.

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

    if(st > dist) {
      $(divid).css("background-image", "url(" + imgurl1 +")");  
    }
    else{
      $(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];
}

you could add 2 background-images to the divid and so they are both loaded at page refresh and then with your JQ toggle between background-images depending on scroll.

see snippet below. let me know if it helps ( i check in Network and both images are loaded when page refresh )

 $(window).scroll(function(){ var st = $(this).scrollTop(); var dist = $("#container").offset().top - 50; if(st > dist) { $("#container").css("background-image", "url(" + "http://i.imgur.com/AsqlqnG.jpg" +")"); } else{ $("#container").css("background-image", "url(" + "http://i.imgur.com/I8170KA.jpg" +")"); } }); 
 #container { background-image : url("http://i.imgur.com/I8170KA.jpg"),url("http://i.imgur.com/AsqlqnG.jpg"); background-size:contain; background-repeat:no-repeat; height:800px; width:100%; margin-top:50px; position:relative; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id ="container"> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM