0

I have an svg tag that has <use> element inside it. The use loads an SVG from some path:

div.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%">
<use xlink:href="${href}" href="${href}" /></svg>`

(Please note it's a string since it's being used for a customElement shadow template).

What I need is a way to detect a 404 on the <use> element in case the href is incorrect.

I tried putting an onerror="()=>{...}" attribute, but it's not being called. Wrapping the with a try/catch block did not help either.

Can anyone please help? Thanks!

Yogev
  • 75
  • 10
  • Perhaps you could check if `href` exists with `XMLHttpRequest` before adding it to the svg... https://stackoverflow.com/questions/10926880/using-javascript-to-detect-whether-the-url-exists-before-display-in-iframe – vanowm Aug 18 '22 at 00:16
  • Thanks. Yeah, I could... I was just hoping to avoid this overhead. – Yogev Aug 18 '22 at 00:49
  • 1
    [Per specs](https://svgwg.org/svg2-draft/interact.html#ErrorEvent) you should have an onerror event firing on your ``, it should even bubble up. But no UA has implemented it for ``. Only `` does fire this event and it doesn't bubble up. (Chrome also has it fire on `` when a script fires an error in a standalone SVG doc.) – Kaiido Aug 18 '22 at 02:06
  • Thanks for this info! So what are my alternatives in that situation? I can't be the only one in need of this, I suppose... – Yogev Aug 18 '22 at 03:25
  • 1
    Unfortunately I'm not aware of a better solution than doing an AJAX request (preferably with "HEAD" headers), but that won't tell you if the resource at the other end is really a valid SVG document with an actual element that has an id matching your fragment identifier (`#`). For this you'd also have to parse the result and search for that element (and even maybe check that this element is actually a graphic element?) All in all, nothing trivial I'm afraid. – Kaiido Aug 18 '22 at 04:19
  • Wow... interesting. That sounds like a problem begging to be solved. Well, thank you for the info again! – Yogev Aug 18 '22 at 04:33
  • 1
    That is why we switched from the oldskool ``use``, to a modern Web Component ```` : https://dev.to/dannyengelman/load-file-web-component-add-external-content-to-the-dom-1nd – Danny '365CSI' Engelman Aug 18 '22 at 08:24

0 Answers0