图片预加载

var myImage = (function() {
    var imgNode = document.createElement('img');
    document.body.appendChild(imgNode);

    var img = new Image();

    img.onload = function() {
        imgNode.src = img.src;
    }

    return {
        setSrc: function(src) {
            imgNode.src = 'images/ajaxing.gif';
            img.src = src;
        }
    }
})();

myImage.setSrc('http://tse4.mm.bing.net/th?id=OIP.puFzgpLnlMDZoFso0eSbIQDIEs&pid=15.1');

虚拟代理实现

var myImage = (function() {
    var imgNode = document.createElement('img');
    document.body.appendChild(imgNode);

    return {
        setSrc: function(src) {
            imgNode.src = src;
        }
    }
})();

var proxyImage = (function() {
    var img = new Image();
    img.onload = function() {
        myImage.setSrc(this.src);
    }

    return {
        setSrc: function(src) {
            myImage.setSrc('images/ajaxing.gif');
            img.src = src;
        }
    }
})();

proxyImage.setSrc('http://tse4.mm.bing.net/th?id=OIP.puFzgpLnlMDZoFso0eSbIQDIEs&pid=15.1');

你可能感兴趣的:(图片预加载)