使用 jQuery 预加载带有图像的内容
我在 jQuery 中使用 .load() 加载 html 内容,但在此内容中嵌入了 3/4 图像。成功事件仅在加载所有 html 而不是实际图像时在 .load() 上触发,有谁知道预加载页面完整内容的方法吗?
$('#ajax_loader').hide().load('page.html',function(){
$(this).fadeUp(1000);
});
这是我的简单代码(其余部分在完整的应用程序中),加载以下代码(即 page.html)
<div>
<div id="slideshow">
<img src="images/img1.jpg" />
<img src="images/img2.jpg" />
<img src="images/img3.jpg" />
</div>
<p>This is some sample content</p>
</div>
I am using .load() in jQuery to load in html content, but in this content there are 3/4 images embedded. The success event only fires on .load() when all the html is loaded in and not actually the images, does anyone know a way of preloading the full content of a page?
$('#ajax_loader').hide().load('page.html',function(){
$(this).fadeUp(1000);
});
This is my simple code (rest of it is in the full app), loading in the following code (ie. page.html)
<div>
<div id="slideshow">
<img src="images/img1.jpg" />
<img src="images/img2.jpg" />
<img src="images/img3.jpg" />
</div>
<p>This is some sample content</p>
</div>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我建议您在图像加载后不要使用
fadeIn
动画,因为它会带来性能下降。通常最好淡入
内容,然后开始加载图像,以确保动画对于尽可能多的用户来说是流畅的。话虽如此,如果你想坚持下去,当然可以实现你最初的目标:
使用 1x1 空白图像作为图像
src
属性,并将真实 URL 存储在title
中。你的代码变成:
I suggest that you don't use a
fadeIn
animation after the images are loaded because of performance degradation it brings. It is usually a good idea tofadeIn
the content then start loading the images to ensure that the animation is smooth for as many users as possible.Having said that, of course you can accomplish your original goal if you want to stick with it:
Use a 1x1 blank image as the image
src
attribute and store the real url in thetitle
.And your code becomes:
这些图像是通过单独的 HTML 请求加载的,显然,在解析响应中的 HTML 之前,浏览器甚至无法开始加载它们。
如果您在加载内容之前知道图像的 URL,则可以通过创建“Image”元素并等待它们加载(即,通过单独处理它们的“load”事件)来预加载它们。
编辑 — @galambalazs 指出处理程序周围的闭包(在本例中)是不必要的。
The images are loaded with separate HTML requests, and obviously the browser can't even start loading them until the HTML in the response has been parsed.
If you know the URLs of the images before you load the content, then you can preload them by creating "Image" elements and waiting for them to load (that is, by handling their "load" events individually).
edit — @galambalazs pointed out that the closure around the handler was (in this case) unnecessary.
查看 这种类似的情况
似乎对您的问题的主要修复是正确的使用
.ready
和.load
运算符。如果使用得当,您可以等到所有元素和媒体项都加载到浏览器中,然后再将响应传递到其处理程序。我不想抄袭太多:)这是一个非常好的答案。Check out this similar situation
It seems that the main fix to your problem would be the correct use of the
.ready
and the.load
operator. If used properly, you can wait until all elements and media items are loaded into the browser before a response is passed to its handler. I don't want to plagerize too much :) and its a really great answer.