0

我想提高此页面上Shadowbox 弹出图像的加载速度

基本上,Shadowbox 打开的所有图像都链接到此页面:

<a href="images/illustration/garden1.jpg" class="garden"></a>
<a href="images/illustration/garden2.jpg" class="garden"></a>

等等等等

我知道如何通过像这样列出它们来预加载图像:

var images = [ 'image1.jpg', 'image2.jpg', ]

$.fn.preload = function() {
    this.each(function(){
        $('<img/>')[0].src = this;
    });
}

$(document).ready(function(){
 $(images).preload();
 });

有没有办法将所有href值拉入预加载数组?如果是这样,我如何排除指向其他文档的链接?还是我做错了?!

谢谢。

4

2 回答 2

0

这是一个使用通配符选择器的纯 JQuery 解决方案

$(function(){
  $('a[href$=".jpg"]').each(function(index, elem){
    var href = $(elem).attr('href');
    $('<img/>')[0].src = href;
  });
});

基本上,$=选择器的意思是'ends-with',所以它会找到任何以 .jpg 结尾的链接并预加载它。如果您使用的是 shadowbox 约定,您可能希望将此选择器更改$('a[rel^="shadowbox"]')为更具体一些。^=意思是“开始”。

于 2013-01-28T09:48:34.530 回答
0

下面的文件将找到在所选文件夹中找到的所有图像(输入到 listImages 函数调用中)。将此作为 all_images.php 保存在您要抓取图像的目录中:

<?php
function listImages($dir){
    $ffs = scandir($dir);
    foreach($ffs as $ff){
        if($ff != '.' && $ff != '..' && strstr($ff, '.png') || strstr($ff, '.jpg') || strstr($ff, '.gif') || strstr($ff, '.jpeg')){
            echo '"/images/'.$ff;
            if(is_dir($dir.'/'.$ff)) listFolderFiles($dir.'/'.$ff);
            echo '", ';
        }
    }
}
echo '[ ';
listImages('images');
echo ']';
// output: ["image1.png", "image2.png"] etc.
?>

然后,为了预加载这些图像,将 all_images.php 文件加载到一个变量中,并预加载它包含的生成的图像文件字符串:

<script src="jquery.js"></script>
<script type="text/javascript">
// put contents of all_images.php file into variable 'images'
$.get('/all_images.php', function (data) {
    images = $(data);
});

// The variable 'images' now contains string of file names
// needed to be preloaded.
$.fn.preload = function() {
    this.each(function(){
        $('<img/>')[0].src = this;
    });
}

$(document).ready(function(){
    $(images).preload();
});
</script>

此解决方案不需要额外的“包含”文件(与我之前的答案不同)。

于 2012-04-16T20:01:42.290 回答