在鼠标单击按钮时,我将 div 中的图像与 Rails 中的另一个部分切换。问题是在该部分加载图像很慢......我想在其中预加载图像。有没有办法做到这一点?我能以某种方式预加载部分内容吗?
在我看来
-@other_images.each do |img|
.thumbnail_wrapper
.thumbnail_image
=image_tag img.image.url(:thumbnail), :class => 'button' , :onClick => "replaceImg(#{img.id});"
js
function replaceImg(id){
var url = '/images/refresh/' + id;
new Ajax.Updater('content_image', url);
}
非常感谢!
最佳答案
我想您的部分是在 View 中呈现的。预加载是欺骗浏览器以确保它需要资源,并且现在就需要它。
Javascript
您可以强制图像在实际以 Javascript 显示之前进行预加载:
<script language="javascript">
function img_preloader() {
myimg = new Image();
images = new Array();
images[0]="image1.jpg";
images[1]="image2.jpg";
images[2]="image3.jpg";
images[3]="image4.jpg";
// start preloading
for(i=0; i<=3; i++) {
myimg.src=images[i];
}
}
</script>
通过这种方式,对于 for
循环中的每次迭代,都会加载一张图像。
要以编程方式生成数组,您可以(在 erb 中):
<script language="javascript">
function img_preloader() {
myimg = new Image();
images = new Array();
<% @array_of_img_paths.each do |path| %>
images.push("<%= path %>");
<% end %>
// start preloading
for(i=0; i<images.length; i++) {
myimg.src=images[i];
}
}
</script>
只是 HTML
- 以编程方式为您要预加载的每张图片打开一个 iframe
- 将 iframe 的 src 设置为您要预加载的图像
- 将 iframe 大小设置得尽可能小
现在根据浏览器和服务器设置并行(预)加载图像。
CSS
将您要预加载的图像设置为任何人都看不到的 div 的背景图像:
div.noone_will_see {
background-image: url("image1.jpg");
background-repeat: no-repeat;
background-position: -1000px -1000px;
}
为您要预加载的每个图像进行迭代。
关于javascript - 使用javascript在rails中预加载部分 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4293822/