jQuery ajax图像预加载
鉴于此,预加载图像:
$('') .attr('src', 'source') .load(function(){ $('.profile').append( $(this) ); // Your other custom code });
你知道如何做同样的几个图像吗?
我试过类似的东西:
var img1 = new Image(); var img2 = new Image(); $(img1).attr('src', 'source1'); $(img2).attr('src', 'source2'); $(img1,img2).load( function () { //code after loading } );
但它不起作用!
有任何想法吗?
最后的尝试
据我所知,你希望能够分辨图像何时加载,并多次执行。 上一次尝试和您自己的代码的问题是“加载”处理程序仅在设置和执行新图像源之后应用。 请尝试以下尺寸:
$(function () { var images = ['image1.jpg','image2.jpg' /* ... */ ]; var imageObjects = []; var imagesToLoad = 0; for (i = 0, z = images.length; i < z; i++) { imageObjects[i] = new Image(); imagesToLoad++; $(imageObjects[i]) .load(function () { if (--imagesToLoad == 0) { // ALL DONE! } // anything in this function will execute after the image loads var newImg = $('').attr('src',$(this).attr('src')); $('.profile').append( $(newImg) ); // I assume this is the code you wanted to execute }) .attr('src',images[i]); // Notice that the 'attr' function is executed AFTER the load handler is hooked } });
[OLD]新的尝试
var images = [ /* you get it by now */ ]; for (i=0,z=images.length;i ') .attr('src', images[i]) .load(function(){ $('.profile').append( $(this) ); // Your other custom code }); }
原始邮政
从这篇文章中获取的想法
$(document).ready(function(){ var images = ["image1.jpg","image2.jpg"]; var loader = new Image(); for (i=0,z=images.count;i
或者,
var images = ["image1.jpg","image2.jpg"]; var loader = []; $(document).ready(function(){ for (i=0,z=images.count;i
您需要创建一个元素数组:
$(img1,img2).load(
应该
$([img1, img2]).load(
做$(img1).attr('src', 'source1');
什么时候可以做img1.src = 'source1';
设置’src’属性时会触发加载。 您必须在设置’src’属性之前注册该事件。 试试这个:
var img1 = new Image(); var img2 = new Image(); $([img1,img2]).load( function () { //code after loading } ); $(img1).attr('src', 'source1'); $(img2).attr('src', 'source2');
希望这可以帮助!
更新
var images = [ /* you get it by now */ ]; for (i=0,z=images.length;i ') .load(function(){ $('.profile').append( $(this) ); // Your other custom code }) .attr('src', images[i]); /* you may also try to add .trigger('load') at the end to force it */ }
-Stephen
function myfun(){ alert("h"); } var xlist = [ "source1", "source2", "source3" ]; var xload = 0; $.each(xlist, function(){ var srcImg = this; $('') .attr('src', srcImg) .load(function(){ xload++; $('.profile').append( $(this) ); if (xlist.length==xload){ // Your other custom code myfun(); } }); });
评论:可以简单地控制加载的图片总量。
我最近经历了这场噩梦。 有几个StackOverflow问题,我提到了图像加载事件令人沮丧的问题 。
跨浏览器实际工作的一种方法是使用计时器并观察图像完整属性(直到它为真)和图像宽度属性(直到它为非零)。 只需旋转所有图像,直到所有图像都符合要求为止。
或者你可以试试Luke Smith的解决方案 。