How to preload images using Vue.js?

前端 未结 3 1519
没有蜡笔的小新
没有蜡笔的小新 2020-12-31 09:43

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 DIV el

相关标签:
3条回答
  • 2020-12-31 10:05

    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".

    example:

    <img :src="images.secondScreenShot" key="secondImage" rel="preload">
    
    0 讨论(0)
  • 2020-12-31 10:10

    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:

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

    You can create a new Image object like so:

    const image = new Image();
    

    Then you can assign a src value to that image:

    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.

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

    0 讨论(0)
  • 2020-12-31 10:11

    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

    0 讨论(0)
提交回复
热议问题