使用 jQuery 预加载图像
我在 教程评论(James),我想实现它。
预加载图像的教程方法很冗长,但我喜欢 James 的简化版本,但是,我尝试过实现它,但我没有得到正确的结果。
看来我需要首先设置我的数组,循环遍历该数组,然后创建图像对象并加载它们。然而,当我检查 Firebug 时,我没有看到任何图像加载到缓存中。
$(function(){
var imgArray = ['bghome01.jpg', 'bghome02.jpg', 'bghome03.jpg'];
$.preload = function (imgArray) {
$.each(imgArray, function () {
alert(imgArray);
(new Image()).src = 'Images/' + this;
});
};
});
我将不胜感激的帮助!
I got this snippet of code following a tutorial comment (by James) on Nettuts and I would like to implement it.
The tutorial method of preloading images is long winded but I liked James' shortened version of this, however, I have tried implementing this and I am not getting it right.
It seems I would need to set up my array first, the loop through that array which then creates the image objects and loads them. Yet, when I check my Firebug, I am not seeing any images load into the cache.
$(function(){
var imgArray = ['bghome01.jpg', 'bghome02.jpg', 'bghome03.jpg'];
$.preload = function (imgArray) {
$.each(imgArray, function () {
alert(imgArray);
(new Image()).src = 'Images/' + this;
});
};
});
I'd appreciate the help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在这里,您定义一个函数,但不调用它:
如果您只想加载图像,您可以将其简化为:
或者,您可以用你原来的方法来做,函数定义可以在外部文件中,但是在页面中你需要调用它,如下所示:
我认为这里的混乱来自于
imgArray
是数组和参数,但这是两个独立的东西,如果你给$.preload
参数一个不同的名称,可能会不那么混乱。Right here, you're defining a function, but not calling it:
If you just want to load the images, you can slim it down to this:
Or, you can do it with your original method, the function definition can be in an external file, but in the page you need to call it, like this:
I think the confusion here comes from
imgArray
being the name for the array and the parameter, but these are 2 separate things, it might be less confusing if you gave the parameter to$.preload
a different name.我的猜测是,您没有保留图像对象,因此垃圾收集可能会在加载图像之前将它们丢弃。
有关一些代码,请参阅本文: http://engineeredweb.com /blog/09/12/preloading-images-jquery-and-javascript
请注意,jQuery 没有任何魔法;归根结底都是 JavaScript,所以你的代码一定有问题。因此,如果保持图像对象处于活动状态没有帮助,也许 这篇文章将为您指明正确的方向。
My guess is that you don't keep the image objects around, so the garbage collection might throw them away before the image can be loaded.
See this article for some code: http://engineeredweb.com/blog/09/12/preloading-images-jquery-and-javascript
Note that jQuery doesn't do any magic; it's all JavaScript in the end, so something must be wrong with your code. So if keeping the image objects alive doesn't help, maybe this article will point you in the right direction.
如果我的浏览器只会加载页面上的图像,那么我怀疑这种情况会发生,因为你从未将图像添加到 DOM 中。尝试使用
style="visibility:hidden"
创建一个新的 img 标签并将其添加到 DOM 中。If I where a browser i would only load images that are on the page, so I suspect his happens because you never add the images to the DOM. Try setting creating a new img-tag with
style="visibility:hidden"
an add it to the DOM.