2017-10-19 67 views
1

有沒有方法檢查內聯svg中的<image>是否已加載?普通imgs有一個完整的屬性來檢查<img>是否已被加載,但不是<image>。我只想在圖像尚未加載的情況下添加加載事件偵聽器。檢查是否加載了內聯SVG圖像

以下的Here's a codepen

<svg width="300" height="300"> 
    <image xlink:href="http://placebeard.it/300/300" width="300" height="300"></image> 
</svg> 


<script> 
    var image = document.querySelector('image'); 
    console.log(image.complete) // undefined 
    if (!image.complete && image.complete != null){ // does not work because there is no complete property of svg image, unlike a regular img 
    image.addEventListener('load', function(){ 
     alert('image loaded'); 
    }); 
    } 
</script> 
+0

這應該是 「如果(!image.complete)」 不應該嗎? –

+0

修好了,謝謝。 – Dan0

+0

我已將您的代碼示例恢復爲已損壞的狀態,以避免將來對此問題的讀者感到困惑。 –

回答

0

您仍然可以添加加載事件。沒有屬性可以判斷它是否已經加載。

var image = document.querySelector('image'); 
 
image.addEventListener('load', function(){ 
 
    alert('image loaded'); 
 
});
<svg width="300" height="300"> 
 
    <image xlink:href="http://placebeard.it/300/300" width="300" height="300"></image> 
 
</svg>

+0

當然,但如果圖像在加載事件偵聽器添加之前已經加載,它永遠不會觸發。 – Dan0

0

我的解決辦法是把圖象源中的數據屬性,添加的負載事件偵聽器然後交換在xlink:HREF。適用於Chrome和Firefox。

Codepen

<svg width="300" height="300"> 
    <image xlink:href="http://placebeard.it/300/300" width="300" height="300"></image> 
</svg> 

<script> 
    var image = document.querySelector('image'); 
    image.addEventListener('load', function(){ 
    alert('image loaded'); 
    }); 

    image.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', 
    image.dataset.src); 
</script>