简体   繁体   English

用JavaScript预加载Rails中的部分视图

[英]preloading a partial view in rails with javascript

On a mouse click of a button, I switch out an image in a div with another partial in Rails. 鼠标单击按钮时,我在div中切换了一个图像,在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 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 使用Javascript

You can force the images to preload before being actually shown in 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>

In this way for every iteration within the for loop one of your images are loaded. 这样的内每次迭代for图片的一环被加载。

To programmatically generate the array you can (in erb): 要以编程方式生成数组,您可以(在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 只是HTML

  • programmatically open one iframe for every image you want to preload 以编程方式为要预加载的每个图像打开一个iframe
  • set the src of the iframe to the image you want to preload 将iframe的src设置为您要预加载的图像
  • set the iframe size as tiny as possible 将iframe尺寸设置得尽可能小

Now images are (pre)loaded in parallel according to the browser and server setup. 现在,根据浏览器和服务器设置并行并行(预)加载图像。

CSS CSS

Set the image you want to preload as the background image of a div noone will ever see: 将您要预加载的图像设置为没人能看到的div背景图像:

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. 迭代要预加载的每个图像。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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