Preload images with your mouse 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 that there is no delay when the user moves the mouse over the image? Thanx.

+3
source share
3 answers

, CSS Sprite? (Photoshop), , CSS : hover : visited. .

+6

jQuery, , jQuery.

jQuery, jQuery. 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>
+2

, , Rails Prototype. , 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 download code runs. Maybe something like this:

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

You must make sure that all magic image_tag()is done for the image paths to ensure that the correct image is preloaded.

0
source

Source: https://habr.com/ru/post/1722510/


All Articles