【问题标题】:ajax - check images have loaded before writing to the pageajax - 在写入页面之前检查图像是否已加载
【发布时间】:2011-03-26 06:56:40
【问题描述】:

在我认为这个项目已经完成之后,我刚刚发现了一个问题。它在我的本地服务器上运行良好,但是当我实时推送代码时,图像可能需要半秒钟才能正确加载,导致在加载图像上弹出一个小页面缩略图。呸呸呸

那么发生了什么?好吧,首先在window.load 上运行一个函数,它创建了大量列表项,其中加载 gif 作为 bg 图像。

然后这个函数将<img>标签弹出到第一个列表项中,onload调用第二个函数

第二个函数循环遍历一个 XML 文件并将 xml 中的 URL 包装在一个 <img> 标记中,并将其放入下一个空的 LI 中。这就是问题所在。目前它在实际加载之前将<img src=$variable onload=loadnextimage() /> 放入列表项。

我的代码:

$(window).load(function() {
            txt="";
            for(d=0;d<100;d++)
            {
                txt=txt + "<li class='gif' id='loading"+d+"'></li>"; 

            }
            document.getElementById('page-wrap').innerHTML=txt;
            document.getElementById('loading0').innerHTML="<img src='images/0.jpg' onLoad='loadImages(0)' />";
        });
        function loadImages(i){ 
            i++
            $.ajax
            ({
                type: "GET",
                url: "sites.xml",
                dataType: "xml",
                async: "true",
                success: function(xml) 
                {
                    var img = $(xml).find('image[id=' + i + ']'),
                    id = img.attr('id'),
                    url = img.find('url').text();
                    $('#loading'+i).html('<img src="'+url+'" onLoad="loadImages('+i+')" />').hide();
                    $('#loading'+i).fadeIn();
                }
            });
        }

我觉得如何设置它可能会很棘手,我觉得我可能需要创建一个 img 对象并等待它加载???

一旦页面被缓存,加载显然工作正常,但在他第一次加载时有点痛苦,所以我需要解决这个问题。 欢迎任何建议:)谢谢

【问题讨论】:

    标签: jquery ajax image


    【解决方案1】:

    我遇到了同样的问题。试图得到答案我达到了你的问题。无论如何,我设法解决它的方法是放置:

    <div style="visibility:hidden; position:absolute; margin-left:-10000px;">
       <img src="foo.png" /> 
        // place all the images in here that you eventually will need
    </div>
    

    图像将被异步下载。如果您已经有图像,则不会再次下载它,它将存储在浏览器的缓存中。因此,如果用户在第一页停留 30 秒,那么您的整个网站会更快。好吧,这取决于您网站的大小。但这解决了使用小网站时的问题。

    我知道这不是一个真正的解决方案我会开始赏金你的问题。

    【讨论】:

      【解决方案2】:
      success: function(xml) {
          var img = $(xml).find('image[id=' + i + ']'),
              id = img.attr('id'),
              url = img.find('url').text();
          // hide loading
          $('#loading'+i).hide();
          $('<img src="'+url+'" onLoad="loadImages('+i+')" />').load(function() {
             // after image load
             $('#loading' + i).html(this); // append to loading
             $('#loading'+i).fadeIn(); // fadeIn loding
          });
      }
      

      【讨论】:

        【解决方案3】:

        在我看来,你的想法很艰难。有时解决办法是改变思维方式。这完全取决于你。 One of my favorite related books.

        我的建议是类似于下面的代码。这不是您所需要的,但是...

        Demo on Fiddle

        HTML:

        <div class="frame" title="Tochal Hotel">
            <div class="loadingVitrin">
                <img src="http://photoblog.toorajam.com/photos/4cf85d53afc37de7e0cc9fa207c7b977.jpg" onload="$(this).fadeTo(500, 1);">
            </div>
        </div>​
        

        CSS:

        html, body {
            padding: 10px;
        }
        
        .frame {
            z-index: 15;
            box-shadow: 0 0 10px gray;
            width: 350px;
            height: 350px;
            border: gray solid 1px;
            padding: 5px;
            background: #F0F9FF;
        }
        
        .loadingVitrin {
            z-index: 15;
            width: 350px;
            height: 350px;
            overflow: hidden;
            background: url("http://photoblog.toorajam.com/images/main/ajax-loader.gif") no-repeat center;
        }
        
        .loadingVitrin img {
            display: none;
            height: 350px;
        }
        ​
        

        【讨论】:

          【解决方案4】:

          感谢@thecodeparadox 我最终得到了:

          $.get("SomePage.aspx", "", function (r) {
          
              // r = response from server
          
              // place response in a wrapper
              var wrapper = $('<div id="wrapper" style=""></div>').html(r);
          
              // need to write the images somewhere in the document for the event onload to fire
              // loading content is a hidden div in my document.
              $(document).append(wrapper);
              //$("#LoadingContent").html("").append(wrapper);
          
              var counter = 0;
          
              var images = $(wrapper).find("img"); // get all the images from the response
          
              // attach the onload event to all images
              images.bind("load", function () {
          
                  counter++;
          
                  if (counter == images.size()) { // when all images are done loading
                      // we are now save to place content
                      // place custom code in here
                      // executeSomeFuction();
                      $("#AjaxContent").html(r); 
                      $(document).remove(wrapper);
                  }
              });
          
          }, "text");
          

          【讨论】:

            【解决方案5】:

            您只需使用 Image() 对象预加载每个图像。 下面给出的脚本非常易于使用。只需在“callbackFN()”中写入您想要执行的任何代码,然后在“preload_images(array_img)”中写入。更准确地说:

               var array_images = [];
               $.ajax
                        ({
                            type: "GET",
                            url: "sites.xml",
                            dataType: "xml",
                            async: "true",
                            success: function(xml) 
                            {
                                var img = $(xml).find('image[id=' + i + ']'),
                                id = img.attr('id'),
                                url = img.find('url').text();
                                array_images.push(url);
                            }
                        });
            
            
            
            
            // Your callback function after loading:
            function callbackFN() {
               // Do whatever you want HERE
               // Pretty much this:
               for (var i = 1; i<=array_images.length; i++) {
                  $('#loading'+i).html('<img src="'+url+'" />').hide();
                  $('#loading'+i).fadeIn();
               }
            }
            
            
            var array_obj = Array();
            var iKnowItsDone = false;
            // Timer (IE BULLET PROOF)
            var ieCheckImgTimer;
                    // Check if images are loaded
                function images_complete(obj) {
                    var max = obj.length;
                    var canGo = true;
                    for (var i = 0; i<max; i++){
                        if (!obj[i].complete) {
                            canGo = false;
                        }
                    }
                    return canGo;
                }
                // Loop to check the images
                function preload_images(obj) {
                    var max = obj.length;
                    for (var i = 0; i<max; i++){
                        var img = new Image();
                        img.src = obj[i];
                        array_obj.push(img);
            
                        img.onload = function() {
                            check_img();
                        }
                    }
                    ieCheckImgTimer = setTimeout('check_img()',250);
                }
            
                    // Timer to see if all the images are loaded yet. Waits till every img are loaded
                function check_img() {
                    if (ieCheckImgTimer) {
                        clearTimeout(ieCheckImgTimer);
                    }
                    if (images_complete(array_obj) && !iKnowItsDone) {
                        iKnowItsDone = true;
                        callbackFN();
                    }
                    else {
                        ieCheckImgTimer = setTimeout('check_img()',250);
                    }
                }
            

            【讨论】:

              【解决方案6】:

              试试这个:

              ThumbImage = document.createElement("img");
              ThumbImage.src = URL;
              
              ThumbImage.onload = function(){
                  //function After Finished Load                      
              }
              

              【讨论】:

                【解决方案7】:

                在将图像添加到文档之前,您要确保图像已由浏览器加载,即在浏览器的缓存中:

                // create an image element
                $('<img />')
                    // add a load event handler first
                    .load(function() {
                        // append the image to the document after it is loaded
                        $('#loading').append(this);
                    })
                    // then assign the image src
                    .attr('src', url);
                

                所以对于你的代码我会这样做:

                $(window).load(function() {
                    var txt="";
                    for(var d=0;d<100;d++)
                    {
                        txt=txt + "<li class='gif' id='loading"+d+"'></li>"; 
                
                    }
                    document.getElementById('page-wrap').innerHTML=txt;
                
                    $('<img />')
                        .load(function() {
                            $('#loading0').append(this);
                            loadImages(0);
                        })
                        .attr('src', 'images/0.jpg');
                });
                function loadImages(i){ 
                    i++
                    $.ajax
                    ({
                        type: "GET",
                        url: "sites.xml",
                        dataType: "xml",
                        async: "true",
                        success: function(xml) 
                        {
                            var img = $(xml).find('image[id=' + i + ']'),
                            id = img.attr('id'),
                            url = img.find('url').text();
                
                            $('<img />')
                                .load(function() {
                                    $('#loading' + i)
                                        .append(this)
                                        .hide()
                                        .fadeIn();
                                    loadImages(i);
                                })
                                .attr('src', url);
                        }
                    });
                }
                

                也许这只是你的示例代码,但我不明白为什么不能同时加载 0.jpg 和 sites.xml,或者其余的图像:

                $(window).load(function() {
                    var buf = [], d;
                    for (d = 0; d < 100; d++) {
                        buf.push('<li class="gif" id="loading' + d + '"></li>');
                    }
                    $('#page-wrap').html(buf.join(''));
                
                    $('<img />')
                        .load(function() {
                            $('#loading0').append(this);
                        })
                        .attr('src', 'images/0.jpg');
                
                    $.ajax({
                        type: 'GET',
                        url: 'sites.xml',
                        dataType: 'xml',
                        async: true,
                        success: function(xml) {
                            var img, id, url, i;
                
                            xml = $(xml);
                
                            for (i = 1; i < 100; i++) {
                                img = xml.find('image[id=' + i + ']');
                                id = img.attr('id');
                                url = img.find('url').text();
                
                                $('<img />')
                                    .load(function() {
                                        $('#loading' + i)
                                            .append(this)
                                            .hide()
                                            .fadeIn();
                                    })
                                    .attr('src', url);
                            }
                        }
                    });
                });
                

                【讨论】:

                  猜你喜欢
                  • 1970-01-01
                  • 1970-01-01
                  • 2015-07-11
                  • 1970-01-01
                  • 1970-01-01
                  • 2018-01-08
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  相关资源
                  最近更新 更多