问题描述
我知道有很多jQuery预加载线程,我已经阅读了其中的大多数内容,但似乎仍然找不到解决我问题的方法.
I know there are heaps of jQuery preloading threads, and I've read through most of them but still can't seem to find the solution to my problem.
我有一个定格"动画,该动画是通过jQuery使用队列并基于图像的顺序命名而构建的.在加载所需的所有图像之前,我不希望运行此动画.目前无法选择Spriting,因为针对不同的产品类型有不同的动画,并且所有图像均已由客户端生成.
I have a "stop motion" animation which is built via jQuery using queue and based on the sequential naming of images. I don't want to run this animation until all the images required for it have been loaded. Spriting is not an option at the moment as there are different animations for different product types, and all the images have already been generated by the client.
此刻我的预加载代码如下:
My preload code at the moment is as below:
function preloadImages($img, $frames){
var $imgsrc = $img.attr("src");
var $getext = $imgsrc.split('.');
var $ext = $getext[1];
var $exploded = $getext[0].split('_');
var $newsrc = "";
for (var i=1; i <= $frames; i++){
for (var j=0; j < $exploded.length-1; j++){
$newsrc = $newsrc + $exploded[j] + "_";
}
$newsrc = $newsrc + i + "." + $ext;
var image_preload = new Image();
image_preload.src = $newsrc;
}
}
其中帧是序列中的总图像数(在此阶段为6或12),图像的命名约定如下:
Where frames is the number of total images in the sequence (6 or 12 at this stage), and the naming convention for images is as follows:
Brand_Product_Category_ProductID_SequenceNo.jpg.
Brand_Product_Category_ProductID_SequenceNo.jpg.
我要执行的操作是不加载包含起始图像的div,直到使用准备好文档中的以下代码片段预加载了所有这些图像为止,但这似乎无法正常工作,即,在所有必需的图像都已预加载之前就显示了holder,因此动画无法顺利运行.
What I'm trying to do is not load up the div holding the starting image until all of these images have been preloaded using the snippet below in document ready, but this doesn't seem to be working correctly, i.e., the holder is shown before all the required images have been preloaded, and consequently the animation doesn't run smoothly.
$(".holder").hide();
preloadImages($(".holder img"), 6);
$(".holder").fadeIn("slow");
我想我需要某种回调,尽管我不确定如何实现.
I guess I need some sort of callback, though I'm not sure how to implement it.
推荐答案
问题是这样的:
当您将值分配给Image
对象的src
字段时,它只是这样做:更改src
属性.浏览器仍然需要从src
属性指向的任何位置加载图像.
When you assign a value to the src
field of an Image
object, it does just that: changes the src
attribute. The browser still needs to load the image from wherever the src
attribute points.
您可以为Image的"load"事件定义一个处理程序...,因此您将需要沿这些内容使用某些内容.
You can define a handler for the 'load' event of an Image... so you're going to need to use something along those lines.
一种方法是定义需要加载的图像列表.每次加载图像时,在数组中设置一个标志.定期检查数组,并在设置所有标志(表明所有图像都已加载)之后,可以淡入div
.
One approach would be to define a list of images that need to be loaded. Each time an Image is loaded, set a flag in the array. Periodically, check the array and, once all the flags are set, indicating that all images are loaded, you can fade in your div
.
这篇关于jQuery预加载动画图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!