有时候页面上的图片非常多,笔者最近做了个本地门户网琴岛搜  http://www.qindaosou.com正好用到,比如一个大量图片的营销型单页面,如果不采取一些延时按需要加载图片一次性读入图片,页面会加载很长时间,用户体验大大的不好。这个jquery插件实现按需要延时加载图片和ajax方式加载页面,jquery代码短小精悍。灰常给力,给力就到琴岛搜论坛,表示支持工作。<script type="text/javascript" src="http://lib.sinaapp.com/js/jquery/1.4.1/jquery.min.js"></script>
<script type="text/javascript" src="jq.scrollLoading.js"></script>
<script>
$(function() {
    $(".scrollLoading").scrollLoading();
});
</script>
按需要延时加载图片和ajax方式加载页面jQuery插件代码:
(function($) {
    $.fn.scrollLoading = function(options) {
        var defaults = {
            attr: "data-url"    
        };
        var params = $.extend({}, defaults, options || {});
        params.cache = [];
        $(this).each(function() {
            var node = this.nodeName.toLowerCase(), url = $(this).attr(params["attr"]);
            if (!url) { return; }
            //重组
            var data = {
                obj: $(this),
                tag: node,
                url: url
            };
            params.cache.push(data);
        });
        
        //动态显示数据
        var loading = function() {
            var st = $(window).scrollTop(), sth = st + $(window).height();
            $.each(params.cache, function(i, data) {
                var o = data.obj, tag = data.tag, url = data.url;
                if (o) {
                    post = o.offset().top; posb = post + o.height();
                    if ((post > st && post < sth) || (posb > st && posb < sth)) {
                        //在浏览器窗口内
                        if (tag === "img") {
                            //图片,改变src
                            o.attr("src", url);    
                        } else {
                            o.load(url);
                        }    
                        data.obj = null;        
                    }
                }
            });        
            return false;    
        };
        
        //事件触发
        //加载完毕即执行
        loading();
        //滚动执行
        $(window).bind("scroll", loading);
    };
})(jQuery);

解决方案 »

  1.   

    1. 放上loading 的圖標
    2. 使用ajax去抓取圖片的路徑
    3. 圖片預載
    var img = new Image();
    img.src = 'test.jpg';
    img.onload = function () {
        alert('ok');
        var width = img.width;
        var height = img.height;
        alert('width : ' + width);
        alert('height : ' + height);
    };
    這可以在圖片載完後抓取到圖片的高和寬,已測試過在firefox、ie6~9、chrome均能運行
    如果是圖片的陣列就在onload 做加減,count 到和陣列的length 代表預載完成4. 將圖片插入到body 中
    document.getElementsByTagName('body')[0].appendChild(img);4.5 插入並做動態
    document.getElementsByTagName('body')[0].appendChild(img);
    function imgFadeIn( img ) {
        var opacity = 0;
        img.style.opacity = opacity;    function ani(){
            opacity += 0.01;
            img.style.opacity = opacity;        
            if (opacity < 1) setTimeout(ani, 16);
        }
        ani();
    }
    imgFadeIn( img );5. 收起loading 的圖標相信以樓主的實力可以自行產出一個很棒的套件!
    加油!