1

This is verrrrry similar to some existing questions:

javascript, image onload() doesnt fire in webkit if loading same image

image.onload event and browser cache

Except that instead of trying to load an html image, I'm working with a svg image. I have a SVG element on the page and a variable containing a data URI string. I want to create a image element, set it to display the data URI, and add it to the SVG element on the page. Here's my code:

var svg=document.getElementsByTagName('svg')[0]
var placed=document.createElementNS("http://www.w3.org/2000/svg", 'image')
placed.addEventListener('load',function(){
    alert('loaded')
})
placed.setAttribute("href",test)
placed.setAttribute("x",100)
placed.setAttribute("y",100)
placed.setAttribute("height",100)
placed.setAttribute("width",100)
svg.appendChild(placed);

Where test is the data URI. This fires appropriately in Firefox and Chrome (and the image loads fine). It does not fire in Safari. I assume this is the same issue as the SO questions I linked above but trying to 'clear' the variable as suggested in some of those answers doesn't seem to do anything and I'm wondering if I need to do something more.

Here's a fiddle that should work great in Firefox/Chrome, not so great in Safari:

https://jsfiddle.net/362pbcLn/

If this is in fact the same caching issue, what do I need to do to clear the variable and get Safari to trigger the load listener?

Community
  • 1
  • 1
AustinC
  • 826
  • 1
  • 8
  • 23

1 Answers1

0

For Safari (and Firefox) you need to change the href setter to

placed.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",test)

Firefox will likely support the simplified href only syntax fairly soon but there's no reason to use it the line above works on Chrome and IE Edge too.

Robert Longson
  • 118,664
  • 26
  • 252
  • 242
  • I've updated the fiddle - this does correct an issue and now the image loads in Safari but it still doesn't fire the load eventlistener. – AustinC Aug 02 '16 at 18:31
  • I guess it's not implemented in Safari then. Raise a bug on the [webkit bugtracker](https://bugs.webkit.org/) – Robert Longson Aug 02 '16 at 18:35