下载图像的加载器

时间:2019-08-26 08:44:10

标签: javascript vuejs2 vue-router

我正在寻找预加载器(旋转加载器,以演示图像正在后台加载)。 此预加载器应在加载CSS背景时显示。

背景故事: 我为SPA本身配备了一个全局预加载器,因此当在后台下载SPA时,用户会看到一个加载器。

但是,当用户导航到带有图像的其他页面时,这些新图像必须由用户的浏览器下载,并且不会触发全局预加载器。

在下载完所有图像或有替代解决方案之前,我该怎么做才能显示现有的加载器?


使用jQuery的解决方案是使用$(document).ready,以在文档准备好后删除已加载的内容。但是,我正在努力寻找VueJS的解决方案。


目前,我看到的解决方案是使用类似于以下内容的内容:https://vuejsexamples.com/a-vue-component-for-showing-loader-during-image-loading/,但仍然无法处理CSS背景图片。


在下面的主要组件中添加了代码。 mounted()有效。 watcher()显示加载程序,但是当我在eventListener中添加watcher()时,不会触发监听。

export default {
  mounted() {
    window.addEventListener("load", () => {
      let element = document.getElementById("global-loader");
      element.style.display = "none";
    });
  },
  watch: {
    $route(to, from) {
      let element = document.getElementById("global-loader");
      element.style.display = "block";
      // I dont know on how to switch global loader off after page switch took place and images were loaded
    }
  }
};

为此,我尝试使用路由器导航,但是未触发addEventListener,因为页面已加载:

router.beforeEach((to, from, next) => { 
    let element = document.getElementById("global-loader");
    element.style.display = "block";

});

router.afterEach((to, from, next) => { 
    window.addEventListener("load", () => {
        let element = document.getElementById("global-loader");
        element.style.display = "none";
      });
});

2 个答案:

答案 0 :(得分:2)

  

How can I check if a background image is loaded?

您似乎无法在CSS背景图片上监听加载事件。

如链接的文章所述,您可以做的是使用常规的<img>标签并监听其load事件。这是Vue组件中的样子:https://codesandbox.io/embed/loading-css-basckground-images-n4nf2

在上面的示例中,

ImageLoadHack.vue就是神奇的地方

答案 1 :(得分:0)

好吧,您总是可以在Vue组件内做同样的事情吗?

我已经有一段时间没有使用Vue了,但是您可以执行以下操作吗:

...
mounted() {
    window.addEventListener('load', () => {
         // this is the same thing as "$(document).ready", do whatever you want here. Page is loaded.
    })
},
...