Created
October 12, 2017 15:13
-
-
Save hfknight/71c987739496892d8b1ee81b9d930be2 to your computer and use it in GitHub Desktop.
JS Proxy Pattern: Image Lazy Load
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Provide a surrogate or placeholder for another object to control access to it. | |
// 常用的虚拟代理形式:某一个花销很大的操作,可以通过虚拟代理的方式延迟到这种需要它的时候才去创建 | |
//(例:使用虚拟代理实现图片懒加载) | |
// 图片懒加载的方式:先通过一张loading图占位,然后通过异步的方式加载图片,等图片加载好了再把完成的图片加载到img标签里面。 | |
var imgFunc = (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() { | |
imgFunc.setSrc(this.src); | |
} | |
return { | |
setSrc: function(src) { | |
imgFunc.setSrc('./loading,gif'); | |
img.src = src; | |
} | |
} | |
})(); | |
proxyImage.setSrc('./pic.png'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment