Frank Weindel
Frank Weindel

Reputation: 1282

Add listener to SVG unload event when SVG is loaded within an <object> tag

I've got an SVG file that I'm loading within an element. I attach a listener to the 's load event. This event is fired when the SVG file is displayed and ready for any manipulation. After the load event I use javascript on my app layer to manipulate the SVG. Hide/show certain elements, animate some elements, add or remove elements. This is all working fine so far and is supported in all the major browsers.

(In case you're curious, I'm doing this because this SVG is part of a reusable component and this was recommended to me as a way to isolate SVG element IDs from ever overlapping with those in the app or other instances of the SVGs.)

A problem arises when the <object> element or some parent of the element gets detached from the document. This causes the <object> to unload. When the detached element is reattached the <object> is automatically reloaded and the load event fires again.

What I'm concerned about most here is being notified when the <object> element is unloaded. I need to run some code to prevent any further SVG manipulation on the unloaded <object>.

There is supposedly an 'unload' event that is fired on the <svg> when this unloading occurs. I'm able to attach a handle to this event ONLY within the SVG file itself as an attribute. Like:

<svg ... onunload="javascript:console.log('THIS WORKS')">

However there seems to be no way within javascript on my app layer to attach to this event. Assuming theObjectEl is a reference to my <object> I'd expect the following to work:

theObjectEl.contentDocument.rootElement.addEventListener(
    'unload',
    function() {
        console.log("THIS DOES NOT WORK");
    }
);

Whats funny is I'm able to get the onunload attribute used in the first example, with theObjectEl.contentDocument.rootElement.attributes.onunload. But setting the attribute does absolutely nothing to change the handler of the event.

A demo showing how the SVG object gets unloaded and reloaded

Any ideas?

Note: The SVG is hosted on the same server as my application so there are no cross-origin restrictions at play.

Upvotes: 0

Views: 577

Answers (1)

Kaiido
Kaiido

Reputation: 136648

Edit

Got it : svgDocument.defaultView.addEventListener('unload' , function(){console.log('Gotcha!')})

You have to attach the event to the documentElement's defaultView property.

Upvotes: 1

Related Questions