[英]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. 当用户滚动到该div的末尾时,我正在更改div的背景。 Since its a fixed background, I am not using HTML
<img>
tag, instead I am using the CSS background-image:
. 由于它是固定的背景,我不使用HTML
<img>
标签,而是使用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. 使用以下
JavaScript
函数,它在我需要时成功更改背景,并在用户滚动回顶部时恢复。
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 +")");
}
});
}
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.
与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
). (在您
body
的末尾添加脚本)。
Explanation: When you create an Image
and set is the src
property the image file download to your browser. 说明:创建
Image
并设置src
属性时,映像文件将下载到浏览器。
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. 您可以将2个
background-images
添加到divid
,因此它们都会在页面刷新时加载,然后使用JQ在background-images
之间切换,具体取决于滚动。
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.