虚拟代理实现图片预加载
1. 代码如下
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="Generator" content="EditPlus®"> <meta name="Author" content=""> <meta name="Keywords" content=""> <meta name="Description" content=""> <title>with proxy CREATE PRELoade imgs</title> </head> <body> <script> /* 创建本体对象,负责在页面中创建img标签, 并且提供setSrc接口设置src属性 */ var myImage = (function(){ var imgNode = document.createElement('img'); document.body.appendChild(imgNode); return{ setSrc:function(src){ console.log(this); imgNode.src = src; } } })(); /* 引入代理对象,通过这个对象,图片在正在被加载 之前,会有有个loading图,提示图片正在加载 */ var proxyImg = (function(){ var img = new Image; img.onload = function(){ myImage.setSrc(this.src); } return{ setSrc:function(src){ myImage.setSrc('imgs/load.gif'); img.src=src; } } })() /* from proxyImg we get myImage */ proxyImg.setSrc('https://files.cnblogs.com/files/vali/timg.bmp'); </script> </body> </html>