javascript - 延迟加载背景图像闪烁

标签 javascript html css

我将网站的所有 javascript 保存在一个大文件中 - my_scripts.js。在所有页面上,我推迟加载此文件(使用内联 javascript)。它是最后加载的内容。

因为我的 HTML 正文使用了大背景图片,所以我认为延迟加载该图片是个好主意。从我的 body css 类中,我删除了这部分:background-image: url('my_background.jpg');

然后,作为我的 my_scripts.js 的第一行,我添加了这个:document.body.style.backgroundImage = "url(my_background.jpg)";

现在,显示背景图像所需的 css 已使用 javascript 添加到我的主样式表中。有效,在加载其他所有内容后大背景加载。

但是:当我在页面之间导航时,背景图像会闪烁。每次都会加载。我究竟做错了什么? my_scripts.js 应该在浏览器的缓存中!为什么会闪烁?

编辑:如果我用

预加载图像,仍然会闪烁
if (document.images) {
img1 = new Image();
img1.src = "my_background.jpg";
}

最佳答案

使用 background-image:url('my_background.jpg)"; 而不是 document.body.style.backgroundImage = "url(my_background.jpg)"; ,因为简单地说,您的 CSS 规则没有闪烁。很简单。

关于javascript - 延迟加载背景图像闪烁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26254010/

相关文章:

javascript - 'atob' : The string to be decoded is not correctly encoded 上出现错误 'Window'

html - 导航栏中的垂直居中文本

javascript - Web 浏览器存储 : Security implications of allowing user-supplied Strings to be evaluated?

css - adobe flash builder 4 : css type selectors are not supported in components spark. components.Label

html - nth-of-type 选择了错误的元素

javascript - 如何在外部 CDN 脚本失败时异步回退? (异步/延迟)

Javascript:无法将字符串转换为数字

javascript - 在任何 Canvas 形状周围绘制外边框和内边框

javascript - 如果类在 jQuery 或 JS 中,则将 css 类添加到所有列表元素

javascript - css position absolute 使文本框下降