js to determine whether the image is loaded
background
Sometimes, we need to monitor the image loading and do some processing, such as the following scenario: when the image file is too large, the loading from the server is very slow, and the image window will be blank for a long time, then we need to add to the image A loading state, prompting the user that the picture is loading, and monitoring whether the picture is loaded, when the loading is complete, close the loading state.
Solution
-
Method 1: The complete attribute of img
<template> <img id="imgDom" :src="imgUrl" :loading="imgLoading" /> </template> <script> import { getImgApi } from '@/api/index'; export default { data () { return { imgUrl: '', } }, mounted() { this.getImg(); }, methods: { // 获取图片 getImg() { this.imgLoading = true; getImgApi().then((res) => { this.imgUrl = res.data; // 轮循complete,判断图片是否加载完成 let timer = setInterval(() => { const dom = document.getElementById('imgDom'); if(dom.complete) { console.log('图片加载成功') this.imgLoading = false; clearInterval(timer); } }, 50); }) } } } </script>
-
Method 2: load event
All browsers support the load event of img<template> <img id="imgDom" :src="imgUrl" :loading="imgLoading" /> </template> <script> import { getImgApi } from '@/api/index'; export default { data () { return { imgUrl: '', } }, mounted() { this.getImg(); const dom = document.getElementById('imgDom'); // onload监听,判断图片是否加载完成 dom.onload = function() { console.log('图片加载成功'); this.imgLoading = false; } }, methods: { // 获取图片 getImg() { this.imgLoading = true; getImgApi().then((res) => { this.imgUrl = res.data; }) } } } </script>
-
The readystatechange event
readyState is complete and loaded, indicating that the image has been loaded. Test that IE6-IE10 supports this event, but other browsers do not.<template> <img id="imgDom" :src="imgUrl" :loading="imgLoading" /> </template> <script> import { getImgApi } from '@/api/index'; export default { data () { return { imgUrl: '', } }, mounted() { this.getImg(); const dom = document.getElementById('imgDom'); // onreadystatechange监听,判断图片是否加载完成 dom.onreadystatechange = function() { if(dom.readyState=="complete"|| dom.readyState=="loaded"){ console.log('图片加载成功'); this.imgLoading = false; } } }, methods: { // 获取图片 getImg() { this.imgLoading = true; getImgApi().then((res) => { this.imgUrl = res.data; }) } } } </script>
article reference
https://tool.4xseo.com/a/6148.html