【问题标题】:JavaScript: Load an image from javascript then wait for the "load" event of that imageJavaScript:从 javascript 加载图像,然后等待该图像的“加载”事件
【发布时间】:2013-11-14 02:47:17
【问题描述】:

我有一个显示高质量图片的页面。图片通常需要一段时间才能加载。我有一个在加载图片#image 时运行的 jQuery 函数我希望这个函数按照它们出现的顺序一次预加载其他图像 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 事件以运行刚刚创建的函数。

我相信这个问题的答案和this question有些关系

【问题讨论】:

  • 为什么不把图片放在容器里,设置一个loading.gif作为背景,让图片自己加载呢?
  • @elclanrs 我想优先考虑图片,以便按使用顺序加载它们。从正在显示的图片开始,它应该尽可能快地加载,而下一张图片应该在第一张图片加载后立即预加载。之后的图片应该加载下一个,它应该继续下去。
  • 您可以使用延迟,链接回调来做到这一点。 api.jquery.com/category/deferred-object
  • 我已对我的问题进行了编辑以显示更多我的代码。我使用了以下问题中的许多想法来创建上面显示的代码片段

标签: html javascript image jquery server-side-scripting


【解决方案1】:

首先创建这样的图像的 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);
  }

}

希望这个小sn-p能帮到你。

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

【讨论】:

    【解决方案2】:

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

    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.");
        }
    });}
    

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

    【讨论】:

      【解决方案3】:

      如果你有图片的url数组,你可以这样做:demo

      <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>
      

      或者,如果您的页面中有图片标签,您可以使用以下内容:demo

      <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>
      

      【讨论】:

        猜你喜欢
        • 2011-01-21
        • 1970-01-01
        • 2016-10-17
        • 2018-02-20
        • 1970-01-01
        • 2014-01-20
        • 2011-08-21
        • 2014-11-15
        • 1970-01-01
        相关资源
        最近更新 更多