javascript Javascript异步加载背景图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6206435/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 19:50:51  来源:igfitidea点击:

Javascript load background-image asynchrously

javascriptjqueryjquery-uihtmlcss

提问by VAShhh

Is it possible to load a background-image asynchronously?

是否可以异步加载背景图像?

Ive seen many jQueryplugins to load normal image in an asynchronous way, but I cant find if it's possible to preload / asyncronously load a background-image.

我见过很多jQuery插件以异步方式加载普通图像,但我找不到是否可以预加载/异步加载背景图像。

EDIT

编辑

I clarify my problem. I've been working on this test site http://mentalfaps.com/The background image is loaded randomly from a set of images refreshed each hour by a chron job (wich takes random images on a flickr catalog).

我澄清我的问题。我一直在这个测试站点上工作http://mentalfaps.com/背景图像是从一组图像中随机加载的,这些图像由 chron 作业每小时刷新一次(在 flickr 目录上随机获取图像)。

The host is free and slow at the moment, so the background image takes some time to load.

主机目前空闲且速度较慢,因此加载背景图像需要一些时间。

The positioning of the first overlay (the one with the PNG transparent mentalfaps logo) and width are regulated by a function created in the jQuery(document).readycostruct.

第一个叠加层(带有 PNG 透明 mentalfaps 徽标的叠加层)的定位和宽度由在jQuery(document).readycostruct 中创建的函数调节。

If you try to refresh the page many times, the width of the right overlay div is 0 (and so you see a "hole" in the layout)

如果您尝试多次刷新页面,则右侧叠加层 div 的宽度为 0(因此您会在布局中看到一个“洞”)

Here is the method to set my positions :

这是设置我的位置的方法:

function setPositions(){
    var oH = $('#overlay-header');
    var overlayHeaderOffset = oH.offset();
    var overlayRightWidth = $(window).width() - (overlayHeaderOffset.left + oH.width());
    if (overlayRightWidth >= 0) {
        $('#overlay-right').width(overlayRightWidth);
    } else {
        $('#overlay-right').width(0);
    }
    var lW =  $('#loader-wrapper');
    lW.offset({
        left: (overlayHeaderOffset.left + oH.width() - lW.width())
    });
}

The problem is that the $(window).width()is lower then the effective window width! so the check fails and the script goes for $('#overlay-right').width(0);

问题是$(window).width()低于有效窗口宽度!所以检查失败,脚本继续$('#overlay-right').width(0);

any ideas?

有任何想法吗?

采纳答案by VAShhh

Ive found the answer myself, it was a problem due to the .offset()method that gived sometimes the wrong values.

我自己找到了答案,这是由于.offset()有时给出错误值的方法造成的问题。

I had the write values using the .position():

我使用以下方法获得了写入值.position()

 var overlayHeaderOffset = oH.position();

回答by Pekka

Not sure whether I really understand your question, but background images (and all other images) are already loaded asynchronously - the browser will start separate requests for them as soon as it encounters the URL while parsing the HTML.

不确定我是否真的理解你的问题,但背景图像(和所有其他图像)已经异步加载 - 浏览器在解析 HTML 时一旦遇到 URL 就会启动对它们的单独请求。

See this excellent answer for background on loading order: Load and execution sequence of a web page?

请参阅有关加载顺序背景的出色答案:网页的加载和执行顺序?

If you meant something else, please clarify.

如果你的意思是别的,请澄清。

回答by Daniel Baulig

The trick to loading something in the background is to load it once, so the next time when it is loaded it already is in the cache.

在后台加载东西的技巧是加载一次,所以下次加载时它已经在缓存中了。

Put the following at the end of your html:

将以下内容放在 html 的末尾:

<script>
    var img = new Image();
    img.onload = function () {
        document.getElementsByTagName('body')[0].style.backgroundImage = 'background.png';
    };
    img.src = 'background.png';
</script>

回答by btford

You could use a prefetch link in the head.

您可以在头部使用预取链接。

<link rel="prefetch" href="/images/background.jpg">

You should be able to add these links to the head via JavaScript.

您应该能够通过 JavaScript 将这些链接添加到头部。

回答by Teddy

I like to use CSS to fill the background with a color for page load.

我喜欢使用 CSS 为页面加载颜色填充背景。

After DOM ready event, I use jQuery to modify the CSS and add a background image. That way, the image isn't loaded until after page loads. Not sure about async, but this method gives the user a decent experience.

在 DOM 就绪事件之后,我使用 jQuery 修改 CSS 并添加背景图像。这样,直到页面加载后才会加载图像。不确定异步,但这种方法为用户提供了不错的体验。

Example: http://it.highpoint.edu/

示例:http: //it.highpoint.edu/

The right side navigation links have a background image. The page initializes with a background color. It is replaced with a background image after page load, via jQuery.

右侧导航链接有一个背景图像。页面初始化为背景色。它在页面加载后通过 jQuery 替换为背景图像。

回答by nikunj

changes in this file jquery.ImageOverlay.js

此文件中的更改 jquery.ImageOverlay.js

set your height and width and enjoy this...

设置你的高度和宽度并享受这个......

imageContainer.css({
            width : "299px",
            height : "138px",
            borderColor : hrefOpts.border_color
        });

回答by Yuri

As it is already mentioned, the background image is loaded asynchronously. If you need to load the background image from JQuery code you may also set the addClass() method to set a CSS class or attr("style=\"background-image:url('myimage.png')\"")

正如已经提到的,背景图像是异步加载的。如果您需要从 JQuery 代码加载背景图像,您还可以设置 addClass() 方法来设置 CSS 类或 attr("style=\"background-image:url('myimage.png')\"")