当用户滚动到该div的末尾时,我正在更改div的背景。 由于它是固定的背景,我不使用HTML <img>标签,而是使用CSS background-image: . 使用以下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 +")"); } }); }我的问题是:
显然,当用户滚动到该偏移时,这会加载图像。 当我托管网站并且用户连接速度慢时,这会让它变慢。 所以我需要在页面开始加载时加载第二个图像。 与Lazy Load相反。 我怎样才能做到这一点?
我真的不想使用任何插件。
任何帮助表示赞赏,提前谢谢!
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 !
最满意答案
您可以在加载前加载它们。 (在您body的末尾添加脚本)。
说明:创建Image并设置src属性时,映像文件将下载到浏览器。
var images = ['img1', 'img2']; for (var i = 0; i < images.length; i++) { var img = new Image(); img.src = images[i]; }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]; }
更多推荐
发布评论