预加载隐藏的CSS图像 [英] preload hidden CSS images

查看:130
本文介绍了预加载隐藏的CSS图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个基于jquery的主页上工作了5个左右隐藏的div,每个包含几个背景CSS图像。

I'm working on a jquery based homepage with 5 or so hidden divs, each containing several background css images.

问题是,浏览器不会加载css图像到DOM,直到父图层的可见性显示,导致图像缓慢加载时,可见。

The issue is that the browser doesn't load css images into the DOM until the visibility of the parent layer is shown, causing images to slowly load in when the layer becomes visible.

我已经考虑过的解决方案:

Solutions I've already considered:


  • CSS sprites

  • 这个jQuery插件,自动加载CSS背景图像(根本不像我所说的许多其他人)。

  • 通过js预加载图片:

  • CSS sprites (too much work to redesign for this, and wont really work when showing/hiding divs)
  • This jQuery plugin that auto-loads CSS background images (simply doesn't work for me as reported by many others).
  • preloading the images via js:

$(function() {
function preloadImg(image) {
  var img = new Image();
  img.src = image;
}

preloadImg('/images/home/search_bg_selected.png');
});

这个解决方案似乎将图像加载到dom两次...当js加载它时,然后再次当加载它的div层变得可见...所以它进行2次HTTP调用,从而不工作。

This solution seems to load the image into the dom twice...once when the js loads it, and then again when the div layer that loads it becomes visible... so it makes 2 HTTP calls, thus not working.

我缺少这个问题的任何其他解决方案?

Any other solutions for this problem that I'm missing?

推荐答案

不使用Javascript?

When you said other ways do you mean ones that don't use Javascript?

<script language="JavaScript">
function preloader() 
{
     // counter
     var i = 0;

     // create object
     imageObj = new Image();

     // set image list
     images = new Array();
     images[0]="image1.jpg"
     images[1]="image2.jpg"
     images[2]="image3.jpg"
     images[3]="image4.jpg"

     // start preloading
     for(i=0; i<=3; i++) 
     {
          imageObj.src=images[i];
     }
} 
</script>

其他没有JS的方法是在你的页面中放置一些html,所以看不到:

Other none JS ways are to place some html in your page somewhere so it's not seen:

<image src="picture.jpg" width="1" height="1" border="0">

或HTML ...

<img src="images/arrow-down.png" class="hiddenPic" />

...和CSS ...

...and CSS...

.hiddenPic {
    height:1px;
    width:1px;
}

更多JavaScript方法: b
$ b

More JavaScript Methods:

function preload(images) {
    if (document.images) {
        var i = 0;
        var imageArray = new Array();
        imageArray = images.split(',');
        var imageObj = new Image();
        for(i=0; i<=imageArray.length-1; i++) {
            //document.write('<img src="' + imageArray[i] + '" />');// Write to page (uncomment to check images)
            imageObj.src=images[i];
        }
    }
}

like:

<script type="text/javascript">
preload('image1.jpg,image2.jpg,image3.jpg');
</script>

这篇关于预加载隐藏的CSS图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆