下面的文件将找到在所选文件夹中找到的所有图像(输入到 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>
此解决方案不需要额外的“包含”文件(与我之前的答案不同)。