简体   繁体   中英

Preload Mouseover Images in Rails

I currently have a rollover button implemented in rails as follows:

<%= image_tag("header/home_but.gif", :mouseover => "header/home_over.gif") %>

How can I preload/cache the mouseover image (home_over.gif) so there is no delay when the user moves their mouse over the image? Thanx.

Are you sure you don't want a CSS Sprite here? Basically you put your image states into one image (Photoshop), set the image as the background of an anchor element, then adjust the visible area with CSS for the background property and the :hover and :visited states. Only one image has to download this way.

My environment uses jQuery, so I wanted the solution to use jQuery as well.

I found another question about preloading images with jQuery, and it's top answer had the jQuery prewritten for me. I adapted my code as follows into ERB:

<% alternate_images = [] %>
<% @resources.each do |resource| %>
  <%= image_tag(resource.primary_image.url, :mouseover => resource.alternate_image.url) %>
  <% alternate_images << resource.alternate_image.url %>
<% end %>
<script type="text/javascript">
$.fn.preload = function() {
    this.each(function(){
        $('<img/>')[0].src = this;
    });
}
$([<% alternate_images.each do |image| %>
     "<%= image %>",
   <% end %>]).preload();
</script>

I'm not a rails programmer, but my understanding is that Rails uses Prototype by default. Assuming that, you could include this JavaScript:

Prototype.preloadImages = function(){
    for(var i=0, images=[]; src=arguments[i]; i++){
        images.push(new Image());
        images.last().src = src;
    }
};

Then add this code wherever your onload code runs. Maybe something like this:

Event.observe(window, 'load', function(){
    Prototype.preloadImages('header/home_over.gif','another/image/to/preload.gif');
});

You'll have to assure that whatever magic image_tag() does is done to the image paths to assure that the correct image is preloaded.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM