Reputation: 1316
On a mouse click of a button, I switch out an image in a div with another partial in Rails. The problem is that loading the image in that partial is slow... I want to preload the image in it. Is there a way to do this? Can I preload the partial somehow?
-@other_images.each do |img|
.thumbnail_wrapper
.thumbnail_image
=image_tag img.image.url(:thumbnail), :class => 'button' , :onClick => "replaceImg(#{img.id});"
function replaceImg(id){
var url = '/images/refresh/' + id;
new Ajax.Updater('content_image', url);
}
Many thanks!
Upvotes: 2
Views: 1040
Reputation: 9728
I suppose your partial are renderd withint the view. Preloading is cheating the browser to make it sure it needs a resource, and it needs it now.
Javascript
You can force the images to preload before being actually shown in 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>
In this way for every iteration within the for
loop one of your images are loaded.
To programmatically generate the array you can (in 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>
Just HTML
Now images are (pre)loaded in parallel according to the browser and server setup.
CSS
Set the image you want to preload as the background image of a div noone will ever see:
div.noone_will_see {
background-image: url("image1.jpg");
background-repeat: no-repeat;
background-position: -1000px -1000px;
}
Iterate for every image you want to preload.
Upvotes: 1