JavaScript:从javascript加载图像,然后等待该图像的“load”事件

JavaScript: Load an image from javascript then wait for the "load" event of that image

本文关键字:图像 load 事件 等待 然后 javascript 加载 JavaScript      更新时间:2023-09-26

我有一个显示高质量图片的页面。 图片通常需要一段时间才能加载。 我有一个在加载图片时运行的 jQuery 函数#image我希望这个函数按照它们出现的顺序一次预加载 1 张其他图像。

所以:如果我在第一张图片上,它应该加载图片 1 并显示它,然后在 pic1 完成后预加载/缓存第二张图片。 正在加载的图片都已附加缓存标头。 当 pic2 完成加载后,pic3 应该开始加载。 如果您想知道,我有一个 cgi 后端,可以循环打印内容等。

到目前为止,我有以下工作:

$('#image').load(function() {
 preLoad2 = new Image()
 preLoad2.src = "pic2"
})

然后,我可以使用具有相同$('#image').load(function() { }行的另一个函数继续此操作,但是我该如何使下一张图片在完全加载之前不会开始加载。 我宁愿不使用定时延迟,因为这不是很准确。

这是我目前拥有的。 在这个例子中,我使用的是 bash cgi 脚本。

#set a loop counter
# variables will be refered to as $[var-name]
count=1
first=true
#loop through all images that need pre-loading
for file in *
  do
    #check if the picture matches the search criteria
    if [[ "$file" = *$lowerSearch* ]]
      then
        #create a js script
        echo "<script language='"javascript'" type='"text/javascript'">"
        echo "function load$count() {"
        echo " preLoad$count = new Image()"
        echo " preLoad$count.src = '"?loadFile=$file'""
        echo "}"
        #the first one of these functions should be bound to the main image load event
        if [ "$first" = 'true' ]
          then
            echo "document.getElementById('image').onload = load$count()"
        #the 2nd and on should be bound to the pre-load of the previous picture
        else
          echo " preLoad$last.onload = load$count()"
        #end if
        fi
        echo "</script>"
        #store the current count so that the next time through it can be used to call the last loaded picture
        last=$count
        first=false
        #add 1 to count
        count=$((count+1))
    #end if
    fi
#end loop
done

工作原理:循环浏览图片。 如果图片符合搜索条件,则运行主代码...否则跳过循环。 在搜索条件中,它会创建一个包含函数的 js 脚本。 该函数加载循环当前引用的图片。 然后,它创建一个 onLoad 函数,该函数引用最后一张预加载的图片,并为其设置 onLoad 事件以运行刚刚创建的函数。

我相信这个问题的回答与这个问题有些关系

首先像这样创建图像的 JSON 记录

var imageRecord = ['image1.jpg',
                'image2.jpg',
                'image3.jpg',
                'image4.jpg',
                'image5.jpg'];

然后创建函数以一个接一个地加载图像

function loadAllImages(index){
  if( index >= imageRecord.length ){
    return;
  }
  //create image object
  var image = new Image();
  //add image path
  image.src = imageRecord[index];
  //bind load event
  image.onload = function(){
    //now load next image
    loadAllImages(index + 1);
  }
}

希望这个小片段对您有所帮助。

要了解使用 JavaScript 预加载图像的整个概念,请访问 http://zainultutorials.blogspot.in/2013/11/preload-images-using-javascript.html

过去我使用过类似于这个图像预加载器的东西:

http://www.webreference.com/programming/javascript/gr/column3/index.html

代码

的格式很奇怪,但代码本身很好。在设置了ImagePreloader"类"之后,我使用了这样的方法:

function preloadImages(imageSRCs){
var loadingMessage = $('<div/>').addClass('loading').html('<h1>LOADING</h1>');
// stay classy: tell the user you're loading images
$('#content').append(loadingMessage);
// this imgPreloader takes care of loading the images
imgPreloader = new ImagePreloader(imageSRCs, function(imgArr, numLoaded){
    if(this.nImages == numLoaded){
        loadingMessage.remove();
        //do whatever you want with the images here
        for(var i = 0; i < imgArr.length; i++){
            var pathIdPattern = new RegExp("[^/]+''.");
            var imgName = pathIdPattern.exec(imgArr[i].src)[0];
            var imgId = imgName.substring(0, imgName.length-1);
            $('div#images').append($(imgArr[i]).hide().attr("id", imgId));
        }
    }else{
        loadingMessage.text('Sorry, there was a problem loading the site : / ');
        console.error("Only " + numLoaded + " of " + this.nImages + " images loaded successfully.");
    }
});}

其中,图像 SRC 参数只是图像路径的字符串数组。也许这是您正在寻找的更复杂的解决方案,但我希望它有所帮助!

如果你有图像一个URL数组,你可以做这样的事情:

演示
<div id="cont"></div>
<script type="text/javascript">
function loadImagesInSequence(images) {
  if (!images.length) {
    return;
  }
  var img = new Image();
    //Remove if from the array list and return it to the variable
    var url = images.shift();
  img.onload = function(){ loadImagesInSequence(images) };
  img.src = url;
    $("#cont").append(img);
}
loadImagesInSequence(['http://www.nasa.gov/centers/goddard/images/content/433226main_Misti_ComaCluster.jpg',
'http://www.hdwallpapers.in/walls/cold_universe-wide.jpg',                     'http://scienceblogs.com/startswithabang/files/2013/05/chemical_composition_universe.jpeg']);
</script>

或者,如果您的页面中有图像标签,则可以使用以下内容:演示

<img id="img1" src="http://miniontours.yzi.me/loading.gif" data-image="http://www.nasa.gov/centers/goddard/images/content/433226main_Misti_ComaCluster.jpg" />
<img id="img2" src="http://miniontours.yzi.me/loading.gif" data-image="http://www.hdwallpapers.in/walls/cold_universe-wide.jpg" />
<img id="img3" src="http://miniontours.yzi.me/loading.gif" data-image="http://scienceblogs.com/startswithabang/files/2013/05/chemical_composition_universe.jpeg" />
<script type="text/javascript">
var imgs = [];
$("img").each(function(){
    imgs.push({
        "ID": this.id,
        "src" : $(this).data("image")
              });
});

loadImagesInSequence(imgs);
function loadImagesInSequence(images) {
    if (!images.length) {
        return;
      }
  var img = images.shift();
  var url = img.src;
  img = $("#"+img.ID);
  img.load(function(){ loadImagesInSequence(images); });
  img.attr("src",url);
}
</script>