css - 预加载 CSS 图像

标签 css image background preloader preload

我有一个隐藏的联系表单,点击按钮即可部署。它的字段被设置为 CSS 背景图像,并且它们总是比已切换的 div 晚一点出现。

我在 <head> 中使用了这个片段部分,但没有运气(在我清除缓存之后):

<script>
$(document).ready(function() {
        pic = new Image();
        pic2 = new Image();
        pic3 = new Image();
        pic.src="<?php bloginfo('template_directory'); ?>/images/inputs/input1.png";
        pic2.src="<?php bloginfo('template_directory'); ?>/images/inputs/input2.png";
        pic3.src="<?php bloginfo('template_directory'); ?>/images/inputs/input3.png";
});
</script>

我正在使用 jQuery 作为我的库,如果我也可以使用它来安排这个问题,那就太好了。

谢谢你的想法。

最佳答案

仅使用 CSS 预加载图像

在下面的代码中,我随机选择了 body 元素,因为它是保证存在于页面上的唯一元素之一。

为了使“技巧”起作用,我们将使用 content 属性,该属性允许轻松地设置要加载的 多个 URL,但如图所示,: :after 伪元素保持隐藏 所以图像不会被渲染:

body::after{
   position:absolute; width:0; height:0; overflow:hidden; z-index:-1; // hide images
   content:url(img1.png) url(img2.png) url(img3.gif) url(img4.jpg);   // load images
}

enter image description here

Demo


最好使用 sprite image减少 http 请求...(如果有许多相对较小的图像)并确保图像托管在 HTTP2 的位置被使用。

关于css - 预加载 CSS 图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1373142/

相关文章:

html - CSS 一半/一半背景

html - 重叠的 Div 部分,无法弄清楚为什么

html - 如何使我的 HTML 表单按钮在移动和桌面浏览器中看起来相同?

html - 是否可以在幻灯片放映之上设置永久图像

html - 背景不会覆盖整个 div

iOS - CGContextStrokePath/CGContextDrawPath 删除黑色背景颜色

css - 如何在窗口大小变化时在多个div中显示消息而不相互重叠

css - 请解释这个CSS

image - Google的图像颜色搜索如何工作?

javascript - 载入大图