开发者

preloading a partial view in rails with javascript

开发者 https://www.devze.com 2023-01-27 10:03 出处:网络
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

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?

in my view

-@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);
}

Many thanks!


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

  • programmatically open one iframe for every image you want to preload
  • set the src of the iframe to the image you want to preload
  • set the iframe size as tiny as possible

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消