- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
- "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html>
- <head>
- <title>Demo</title>
- <script type="text/javascript" src1="https://ajax.googleapis.com/ajax/libs/jquery/1.6.3/jquery.min.js"></script>
- <script type="text/javascript" src1="jquery.imgpreload.min.js"></script>
- //以上两步是引入jquery文件和预加载的插件;
- <script type="text/javascript">
- jQuery(function($)
- {
- $('#status, #domstatus').append('<li> dom ready </li>');
- });
- // cache buster
- var t = (new Date).getTime();//获得当前时间
- var the_images = [];//新建一个数组,然后将要加载的图片地址推入这个数组中;
- the_images.push( 'http://farm7.static.flickr.com/6195/6130724163_9ec1db80c7_b.jpg?i=1&t=' + t );
- the_images.push( 'http://farm7.static.flickr.com/6188/6131273938_c711a28586_b.jpg?i=2&t=' + t );
- the_images.push( 'http://farm7.static.flickr.com/6065/6125251344_c6f089b09f_b.jpg?i=3&t=' + t );
- the_images.push( 'http://farm5.static.flickr.com/4001/4626549119_6c524ace61_b.jpg?i=4&t=' + t );
- the_images.push( 'http://farm6.static.flickr.com/5229/5637847279_3acce67b5f_b.jpg?i=5&t=' + t );
- the_images.push( 'fake-image.jpg?i=6&t=' + t );
- jQuery.imgpreload(the_images,//开始运行预加载;
- {
- each: function()//each的意思是,每次加载完一个图片后,执行此匿名函数中的代码,本例仅仅是将图片的地址打印到页面而已,所以大家不用纠结“为什么没有看到图片”
- {
- var pattern = new RegExp( "i=(\\\\d)", "gi" );
- var m = pattern.exec($(this).attr('src'));
- var status = $(this).data('loaded')?'success':'error';
- $('#status').append('<li>' + m[1] + ': ' + $(this).attr('src') + ' ' + status + '</li>');
- },
- all: function()//all的意思是,当所有图片加载完毕之后,执行此函数体内的内容;举个例子,如果有5张图片需要预加载,则each中的function会执行5次,而all的function 只会执行一次~
- {
- $('#status').append('<li> all images loaded </li>');
- }
- });
- </script>
- </head>
- <body>
- <h3>Status:</h3>
- <ul id="status"></ul>
- <h3>In-dom status:</h3>
- <ul id="domstatus"></ul>
- <div id="images" style="display:none;">
- <script type="text/javascript">
- // cache buster
- //这里差不多一个意思~~
- var t = (new Date).getTime();
- var icnt = the_images.length;
- for (var i=0; i<icnt; i++)
- {
- the_images[i] = the_images[i].replace(/t=\\d*/gi, 't=' + t);
- document.write('<img src="' + the_images[i] + '" alt=""/>');
- }
- </script>
- </div>
- <script type="text/javascript">
- jQuery(function($)
- {
- $('#images img').imgpreload
- ({
- each: function()
- {
- var pattern = new RegExp( "i=(\\\\d)", "gi" );
- var m = pattern.exec($(this).attr('src'));
- var status = $(this).data('loaded')?'success':'error';
- $('#domstatus').append('<li>' + m[1] + ': ' + $(this).attr('src') + ' ' + status +'</li>');
- $(this).addClass('image-loaded');
- },
- all: function()
- {
- $('#domstatus').append('<li> all images loaded </li>');
- }
- });
- });
- </script>
- </body>
- </html>
- //该片段来自于http://www.codesnippet.cn/detail/120920135831.html
来源: http://www.codesnippet.cn/detail/120920135831.html