jQuery - 只加载文档中使用的那些预定义的CSS背景图像?

时间:2011-04-11 09:51:32

标签: jquery css background onload preload

让我们说我有多个具有多个背景图像的div,我想要预装它们,如下面的代码所示。在某些文档中,我没有使用所有这些背景图像,因此仅预加载文档中出现的图像而不是预定义大量的背景图像(即使它们未在文档中使用时也会加载)是有意义的。

我有这个加载图片的代码但是,Id就像只在使用它们时才加载的图像。

$(document).ready(function()
{
    var img = document.createElement('img');

    img.onload = function()
    {
        console.log("%o finished loading", this);
        //Set mouseover/mouseout event here
    };

    img.src = 'image.png', 'image2.png', 'image3.png'; // i realized that i have no idea how to add more images
});

1 个答案:

答案 0 :(得分:1)

我建议您使用数据库或仅传递与您正在查看的文档相关的数组,动态地将图像数组提供给javascript。

所以你可以使用这样的函数:

var BuildImages = function(imgs)
{
  for(var i = 0; i < imgs.length; i++)
  {
    var img = document.createElement('img');

    img.load(function(e)
    {
       console.log("%o finished loading", this);
       //Set mouseover/mouseout event here
    });

    img.src = imgs[i];
  }
}

然后从您的文档中调用它:

$(document).ready(BuildImages(new Array('image.png', 'image2.png', 'image3.png')));

////更新

var buildImages = function(divsclassname, imgs)
{
  var i = 0;
  // Loop through all divs with the class name you pass into this function
  $('.'+divsclassname).each(function(e)
  {
    // Check for has-image
    if(!$(this).hasClass('has-image'))
    {
      // If not found then set the background image and add class
      $(this).css('background-image', imags[i]).addClass('has-image');
    } 
    i++;
  });
}

通过添加设置div的类名

,仍以相同的方式调用该函数
$(document).ready(function(e)
{
  // Define your images in an array
  var images = new Array('image.png', 'image2.png', 'image3.png');

  // pas in the images and the classname of the divs you want to have bg images
  buildImages('yourdivsclassname', images));
});