javascript 如何使用 Vue.js 预加载图像?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48090443/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 07:47:52  来源:igfitidea点击:

How to preload images using Vue.js?

javascriptvue.jspreload

提问by Edi

I have a small app using Vue.Js (with webpack). I have a transition section. When the user clicks to a button the content going to change. It's a simple DIVelement with an IMGchild element. My problem is when the user clicks the button, the next image will be loaded in real-time and it's slow, so somehow I need to preload these images.

我有一个使用 Vue.Js(带有 webpack)的小应用程序。我有一个过渡部分。当用户单击按钮时,内容将发生变化。这是一个DIV带有IMG子元素的简单元素。我的问题是当用户单击按钮时,将实时加载下一张图片,而且速度很慢,所以我需要以某种方式预加载这些图片。

I have tried different approaches but couldn't achive the images be preloaded. The problems:

我尝试了不同的方法,但无法预加载图像。问题:

  • Only the first image is the part of the DOM, when page displayed, so the other images will be not loaded. Ok, it's the normal behavior.

  • I couldn't preload the images by using a simple for-loop on an array of images (Preloading images with JavaScript), because images will be requested by a unique query string (1) to each request. So the preloaded image names will not match with the requested.

  • I tried to load the images using require()and bind it to the IMG tag's srcproperty. It's also not solved my problem, the images will be loaded in real-time after the click when the new DIVwill be inserted into the DOM.

  • 只有第一张图片是DOM的一部分,当页面显示时,其他图片不会被加载。好吧,这是正常行为。

  • 我无法通过对图像数组(使用 JavaScript预加载图像)使用简单的 for 循环来预加载图像,因为1每个请求都会通过唯一的查询字符串 ( ) 来请求图像。所以预加载的图像名称将与请求的不匹配。

  • 我尝试使用加载图像require()并将其绑定到 IMG 标签的src属性。这也没有解决我的问题,当新DIV插入DOM时,图像将在单击后实时加载。

My simplified single file compontent (.vue) looks something like that:

我的简化单文件组件 (.vue) 看起来像这样:

<template>
    <!-- [FIRST] -->
    <div v-if="contentId == 0">
      <transition
        enter-active-class="animated fadeIn"
        leave-active-class="animated fadeOut"
        mode="out-in">
        <img :src="images.firstScreenShot" key="firstImage">
      </transition>
    </div>
    <!-- [/FIRST] -->

    <!-- [SECOND] -->
    <div v-else-if="contentId == 1">
      <transition
        enter-active-class="animated fadeIn"
        leave-active-class="animated fadeOut"
        mode="out-in">

        <img :src="images.secondScreenShot" key="secondImage">
      </transition>
    </div>
    <!-- [/SECOND] -->
</template>
<script>
    export default {
        data() {
            return {
                contentId: 0,
                images: {
                    firstScreenShot: require('./assets/first-screen-shot.png'),
                    secondScreenShot: require('./assets/second-screen-shot.png'),
                }
            }
        }
    }
</script>

I'm new to Vue.js, maybe my approach is not good. Please let me know what is the good approach!

我是 Vue.js 的新手,也许我的方法不好。请让我知道什么是好的方法!

回答by Stephan-v

I quickly tried this out in the browser but it seems to work in console. You can use the Javascript Image object to pre-load images it seems:

我很快在浏览器中尝试了这个,但它似乎在控制台中工作。您可以使用 Javascript Image 对象来预加载图像:

https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/Image

https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/Image

You can create a new Image object like so:

您可以像这样创建一个新的 Image 对象:

const image = new Image();

Then you can assign a src value to that image:

然后您可以为该图像分配一个 src 值:

image.src = 'test.jpg'

When you supply the src property with data immediately a network request will be fired by the browser which should be sufficient for the image to be loaded and cached. This way you don't have to insert these images into the DOM.

当您立即为 src 属性提供数据时,浏览器将触发网络请求,这应该足以加载和缓存图像。这样您就不必将这些图像插入到 DOM 中。

Someone correct me if I am wrong on this though, haven't tried to out fully.

如果我错了,有人会纠正我,但还没有尝试完全解决。

回答by TingSter

I create one function just send the image object you want to load via parameter.

我创建了一个函数,只是通过参数发送要加载的图像对象。

in router

在路由器中

import Digital from '../../images/digital';
import { loadImage } from '../LoadImage';
...

const router = new Router({
  routes: [
    {
      path: '/',
      name: 'welcome',
      component: Welcome,
      beforeEnter(to, from, next) {
         loadImage(Digital);
      }
   }
]

my function

我的功能

export function loadImage(imagesObject) {
  Object.keys(imagesObject).map((key, index) => {
    const img = new Image();
    img.src = imagesObject[key];
  });
}

Hope it help

希望有帮助

回答by Fraccier

If you are using the template to load the image with the tag you can make use of simple HTML to preload the images using rel="preload".

如果您使用模板加载带有标签的图像,您可以使用简单的 HTML 使用rel="preload"来预加载图像。

example:

例子:

<img :src="images.secondScreenShot" key="secondImage" rel="preload">