【研究】加载图片时,同一url,多次request

此前曾经碰到过一个挺奇怪的现象。

同样是一个url,在动态生成图片时,居然会多次请求,不管怎么说让人感觉非常不爽,于是自己写了一段简单的代码实验了一下。

<html>
    <script src="http://static.blog.csdn.net/scripts/jquery.js"></script>
    <script>
        var arr = new Array();
        arr.push("http://info-database.csdn.net/Upload/2012-10-08/sap_im(10-08-10-13-51).jpg");
        arr.push("http://static.blog.csdn.net/images/top.png");
        
        $(function(){
            $("#btn").click(function(){
                var url = $("#imgContent img:last").attr("src");
                console.log(url);
                var i=0,index,len=arr.length;
                $(arr).each(function(){
                    if(this.toString() == url){
                        index = i;
                        index = index +1;
                        if(index >= len){index = 0;}
                        return false;
                    }
                    i++;
                });
                //注释1
                //$("<img src="+arr[index]+" width='100px' height='100px'/>").appendTo("#imgContent");
                //注释2                
                //var newImg = new Image();
                //var src = arr[index];
                //newImg.onload = function(){
                //    $(newImg).appendTo("#imgContent");
                //}
                //newImg.src = src;
                
            });    
        });
    </script>
    <body>
        <div id="imgContent">
            <img id="target" width="100px" height = "100px" src="http://info-database.csdn.net/Upload/2012-10-08/sap_im(10-08-10-13-51).jpg"/>
        </div>
        <input type="button" value="changeImage" id="btn"/>
    </body>
</html>    

代码中注释1和注释2的部分是两种不同的写法。

我在正式的代码中采用的是第一种写法,直接生成一个image对象添加到目标元素后面去。

而第二种写法,是讲图片缓存到一个Image对象中,如果该对象已经下载过,那么直接引用该对象的src,而不是重新进行请求。

从实际结果来看,无论是写法1还是写法2,效果都如下:

也就是说,在这个简单的例子中,添加图片时使用同一url,不会造成多次请求。

那只好证明我原先碰到的那个怪问题,是系统配置所造成的。

俩字:蛋疼!!!!

posted @ 2012-10-09 00:37  のんきネコ  阅读(850)  评论(0编辑  收藏  举报